JavaScript:检查数组是否具有几乎递增的序列

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/1 17:48:17

给定一个整数序列作为数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。

如果 a0 < a1 < ... < an,则序列 a0、a1、...、an 被视为严格递增。仅包含一个元素的序列也被视为严格递增。

示例

对于序列 = [1, 3, 2, 1],输出应为 −

almostIncreasingSequence(sequence) = false。

此数组中没有一个元素可以删除以获得严格递增序列。

对于sequence = [1, 3, 2],输出应为 −

almostIncreasingSequence(sequence) = true。

我们可以从数组中删除 3 以获得严格递增序列 [1, 2]。或者,我们可以删除 2 以获得严格递增序列 [1, 3]。

示例

以下是代码 −

const arr1 = [3, 5, 67, 98, 3];
const arr2 = [4, 3, 5, 67, 98, 3];
const almostIncreasingSequence = sequence => {
   let removed = 0;
   let i = 0;
   let prev = -Infinity;
   while(removed < 2 && i < sequence.length) {
      if(sequence[i] > prev) {
         prev = sequence[i];
      }else{
         prev = Math.min(prev, sequence[i]);
         removed++;
      }
      i++;
   }
   return removed < 2;
};
console.log(almostIncreasingSequence(arr1));
console.log(almostIncreasingSequence(arr2));

输出

这将在控制台上产生以下输出 −

true
false

相关文章


有用资源