有序数组中的最后插入索引

JavaScriptJavaScriptBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索在有序数组中查找最后插入索引的概念。我们将学习如何检查数组是否按降序排序,以及如何使用 Array.prototype.reverse()Array.prototype.findIndex() 来找到元素应插入的合适最后索引。在本实验结束时,你将对如何维护数组的排序顺序有更深入的理解。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("JavaScript")) -.-> javascript/BasicConceptsGroup(["Basic Concepts"]) javascript/BasicConceptsGroup -.-> javascript/variables("Variables") javascript/BasicConceptsGroup -.-> javascript/data_types("Data Types") javascript/BasicConceptsGroup -.-> javascript/arith_ops("Arithmetic Operators") javascript/BasicConceptsGroup -.-> javascript/comp_ops("Comparison Operators") javascript/BasicConceptsGroup -.-> javascript/array_methods("Array Methods") subgraph Lab Skills javascript/variables -.-> lab-28465{{"有序数组中的最后插入索引"}} javascript/data_types -.-> lab-28465{{"有序数组中的最后插入索引"}} javascript/arith_ops -.-> lab-28465{{"有序数组中的最后插入索引"}} javascript/comp_ops -.-> lab-28465{{"有序数组中的最后插入索引"}} javascript/array_methods -.-> lab-28465{{"有序数组中的最后插入索引"}} end

有序数组中最后插入索引的说明

要找到为了保持数组排序顺序,某个值应插入的最高索引,请遵循以下步骤:

  • 首先,大致检查数组是否按降序排序。
  • 然后,使用 Array.prototype.reverse()Array.prototype.findIndex() 来找到元素应插入的合适最后索引。

以下是该函数的代码:

const sortedLastIndex = (arr, n) => {
  const isDescending = arr[0] > arr[arr.length - 1];
  const index = arr
    .reverse()
    .findIndex((el) => (isDescending ? n <= el : n >= el));
  return index === -1 ? 0 : arr.length - index;
};

以下是使用该函数的示例:

sortedLastIndex([10, 20, 30, 30, 40], 30); // 4

要开始练习编码,请打开终端/SSH 并输入 node

总结

恭喜你!你已经完成了“有序数组中的最后插入索引”实验。你可以在 LabEx 中练习更多实验来提升你的技能。