【发布时间】:2017-07-05 00:43:26
【问题描述】:
所以我必须编写一个满足以下要求的函数:
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 次测试,时间限制为 4000 毫秒,但每次都在第 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 循环/迭代的情况下让它运行得更快呢?
【问题讨论】:
-
摆脱
greater()...当它只在一个地方使用并且是一个如此简单的条件时,不需要所有的函数调用 -
问题可能更适合codereview.stackexchange.com
-
另外,greaterThan中for循环的主体可以是
if (arr[i] >= arr[i+1]) return false。 -
有一个 O(n) 的解决方案,你可以用谷歌搜索。您不需要遍历它们 2 次。试着想想你是否能想出一个只循环一次的解决方案。
-
slice()和splice()调用都在每次循环中创建新数组。我会尝试通过提出一种可以对原始序列进行处理的算法来消除这些问题。
标签: javascript arrays performance time sequence