确定数组是否保持几乎增加的序列

时间:2017-11-07 21:48:09

标签: javascript

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

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

almostIncreasingSequence(sequence) === false

为了获得严格增加的序列,此数组中没有一个元素可以删除。

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

almostIncreasingSequence(sequence) === true

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

这是我到目前为止所做的:

function almostIncreasingSequence(sequence) {
  //compare current int to previous, return true if greater than 
  //remove int at index and compare with new values, return false if comparison fails
  var result = false;

  for(var i = 0; i < sequence.length; i++){
     var newSequence = sequence.slice();
     var subSequence = newSequence.splice(i, 1);

     for(var j = 0; j < newSequence.length - 1; j++){
        if(newSequence === newSequence.sort((a,b) => a < b).reverse()){
          result = true;
        } 
     }         
  }
  return result;
}

我正在试图弄清楚如何解决这个问题。我觉得我非常接近,但出于某种原因,当我在条件语句中调用reverse时,它也会对newSequence变量进行排序。它在条件中排序两个变量,而不是一个。结果它解析为真。我不清楚为什么会这样。任何反馈都表示赞赏。

2 个答案:

答案 0 :(得分:5)

不需要使用嵌套循环,也不需要创建新数组。这可以在 O(n)时间内完成:

&#13;
&#13;
function almostIncreasingSequence(sequence) {
    var prev = -Infinity,
        beforePrev = -Infinity,
        allowExceptions = true;
    
    for (var curr of sequence) {
        // Is order not maintained?
        if (curr <= prev) {
            // Give up when this is not the first exception
            if (!allowExceptions) return false;
            allowExceptions = false;
            // Decide whether to skip the current or previous value
            if (curr > beforePrev) prev = curr;
        } else { // Normal case: keep track of two preceding values
            beforePrev = prev;
            prev = curr;
        }
    }
    return true;
}

console.log(almostIncreasingSequence([1,5,3,4,8])); // true
console.log(almostIncreasingSequence([1,5,0,6,8])); // true
console.log(almostIncreasingSequence([1,5,0,4,8])); // false
&#13;
&#13;
&#13;

答案 1 :(得分:1)

sort()修改了数组,它没有返回一个新数组。并且您无法使用==比较两个数组的内容,因此这不是判断数组是否已排序的好方法。您可以简单地遍历数组,测试每个元素是否大于前一个元素。

&#13;
&#13;
function almostIncreasingSequence(sequence) {
  for (var i = 0; i < sequence.length; i++) {
    var newSequence = sequence.slice();
    newSequence.splice(i, 1);
    var isSorted = true;
    for (j = 1; isSorted && j < newSequence.length; j++) {
      if (newSequence[j] <= newSequence[j-1]) {
        isSorted = false;
      }
    }
    if (isSorted) {
      return true;
    }
  }
  return false;
}

console.log(almostIncreasingSequence([1, 3, 2, 1]));
console.log(almostIncreasingSequence([1, 3, 2]));
console.log(almostIncreasingSequence([1, 2, 3, 4, 5, 3]));
console.log(almostIncreasingSequence([8, 1, 2, 3, 4, 5]));
console.log(almostIncreasingSequence([8, 1, 2, 2, 4, 5]));
&#13;
&#13;
&#13;