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

时间:2017-07-05 00:43:26

标签: 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
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
}

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

1 个答案:

答案 0 :(得分:0)

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

  1. 如果序列在索引i没有严格增加,a[i]>=a[i+1]为真,则必须删除a[i]a[i+1]才能使阵列严格增加 - 它们都不能留在原地。

  2. 如果要通过仅删除一个元素来修复输入数组,并且它在i元素之后减少,则必须通过删除带有下标i或{的元素来严格增加它{1}}。

  3. 在返回(i+1)true之前,比较检查原始数组和最多两个子数组的效率,并检查与原始数组长度相同的数组数。我会把代码重新写给你 - 这不是我的作业: - )