javascript:如何让函数运行得更快

javascript:如何让函数运行得更快,javascript,arrays,performance,time,sequence,Javascript,Arrays,Performance,Time,Sequence,因此,我必须编写一个满足以下要求的函数: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. Example: For sequence = [1, 3, 2, 1], the output should be

因此,我必须编写一个满足以下要求的函数:

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example:

For sequence = [1, 3, 2, 1], the output should be
almostIncreasingSequence(sequence) = false;

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2], the output should be
almostIncreasingSequence(sequence) = true.

You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].

Input/Output

[time limit] 4000ms (js)
[input] array.integer sequence

Guaranteed constraints:
2 ≤ sequence.length ≤ 105,
-105 ≤ sequence[i] ≤ 105.
所以我的代码除了一个问题外还能工作——它必须通过30个测试,时间限制为4000ms,但每次都会在第30个测试时超时。我尝试过修改它,使它运行得更快,但每次我这样做,它不再正常工作。虽然从技术上讲,我只需要编写一个函数,但我将其分解为三个单独的函数。这是我的密码:

var greater = function(a, b) {
  if (a < b) {
    return true
  } else {
    return false
  }
}

function greaterThan(arr) {
  for (var i = 0; i < arr.length-1; i++) {
    var curr = arr[i]
    var next = arr[i + 1]
    if (greater(curr, next) === false) {
      return false
    }
  }
  return true
}

function almostIncreasingSequence(sequence) {
  for(var i = 0; i < sequence.length; i++) {
    var newArr = sequence.slice()
    newArr.splice(i, 1)
    if (greaterThan(newArr) === true) {
      return true
    } 
  }
  return false
}
var更大=函数(a,b){
if(a

那么,如何在不使用两个for循环/迭代的情况下让它运行得更快呢

改进算法可能比改进代码带来更好的结果。问题是:

  • 如果序列在索引
    i
    处没有严格增加,以致
    a[i]>=a[i+1]
    为真,则必须删除
    a[i]
    a[i+1]
    以可能使数组严格增加-它们不能同时保留在原位

  • 如果要通过仅移除一个元素来固定输入数组,并且在
    i
    th元素之后它会减小,则必须通过移除下标为
    i
    (i+1)
    的元素来严格增加输入数组


  • 在返回
    true
    false
    之前,将检查原始数组和最多两个子数组的效率与检查与原始数组长度相同的数组数进行比较。我将把重新编写代码留给你-这不是我的家庭作业:-)

    摆脱
    greater()
    。。。如果只在一个地方使用,并且是如此简单的条件问题,则不需要所有函数调用。此外,for循环体的大小可能比
    if(arr[i]>=arr[i+1])返回false
    。有一个O(n)解决方案可以在谷歌上搜索。您不需要在它们之间循环两次。试着想想你是否能想出一个只循环一次的解决方案。
    slice()
    splice()
    调用每次都在循环中创建新的数组。我将尝试通过提出一种算法来消除这些问题,该算法可以对原始序列进行适当的处理。