我遇到了一个问题以及如何解决它。请注意,我是 JavaScript 的新手,我觉得这个问题过于复杂了。
问题:
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.
例子
对于 sequence = [1, 3, 2, 1]
,输出应该是
almostIncreasingSequence(sequence) = false;
为了得到严格递增的序列,这个数组中没有一个元素可以被删除。
对于 sequence = [1, 3, 2]
,输出应该是
almostIncreasingSequence(sequence) = true
。
您可以从数组中删除 3 以获得严格递增序列 [1, 2]
。或者,您可以删除 2 以获得严格递增序列 [1, 3]
。
感谢您的所有评论!我想将其更新为一个更好的问题,并通知您我已经找到了解决方案,如果有人想检查它并查看是否有更简洁的方式来放置它。 :)
function almostIncreasingSequence(sequence) {
if(sequence.length == 2) return true;
var error = 0;
for(var i = 0; i < sequence.length - 1; i++){
if(sequence[i] >= sequence[i+1]){
var noStepBack = sequence[i-1] && sequence[i-1] >= sequence[i+1];
var noStepFoward = sequence[i+2] && sequence[i] >= sequence[i+2];
if(i > 0 && noStepBack && noStepFoward) {
error+=2;
}else{
error++;
}
}
if(error > 1){
return false;
}
}
return true;
}
最佳答案
想想你的代码:
sequence[i+1] - sequence[i] !== 1, variable++;
适用于以下数组:[1,2,3,8,8]
。
从问题描述来看,不清楚程序是否必须删除一个字符。但如果是这样的话,下面的代码应该可以做到。
function canGetStrictlyIncreasingSeq(numbers) {
var counter = 0;
var lastGreatestNumber = numbers[0];
for (var i = 1; i < numbers.length; i++) {
if (lastGreatestNumber >= numbers[i]) {
counter++;
lastGreatestNumber = numbers[i];
} else {
lastGreatestNumber = numbers[i];
}
}
if (counter <= 1)
return true;
return false;
}
var nums1 = [1, 2, 3, 4, 5]; //true
var nums2 = [1, 2, 2, 3, 4]; //true
var nums3 = [1, 3, 8, 1, 9]; //true
var nums4 = [3, 2, 5, 6, 9]; //true
var nums5 = [3, 2, 1, 0, 5]; //false
var nums6 = [1, 2, 2, 2, 3]; //false
var nums7 = [1, 1, 1, 1, 1]; //false
var nums8 = [1, 2]; //true
var nums9 = [1, 2, 2]; //true
var nums10 = [1, 1, 2, 3, 4, 5, 5]; //false
var nums11 = [10, 1, 2, 3, 4, 5]; //true
var nums12 = [1, 2, 3, 4, 99, 5, 6]; //true
console.log(canGetStrictlyIncreasingSeq(nums1));
console.log(canGetStrictlyIncreasingSeq(nums2));
console.log(canGetStrictlyIncreasingSeq(nums3));
console.log(canGetStrictlyIncreasingSeq(nums4));
console.log(canGetStrictlyIncreasingSeq(nums5));
console.log(canGetStrictlyIncreasingSeq(nums6));
console.log(canGetStrictlyIncreasingSeq(nums7));
console.log(canGetStrictlyIncreasingSeq(nums8));
console.log(canGetStrictlyIncreasingSeq(nums9));
console.log(canGetStrictlyIncreasingSeq(nums10));
console.log(canGetStrictlyIncreasingSeq(nums11));
console.log(canGetStrictlyIncreasingSeq(nums12));
关于使用 for 循环或 switch 语句的 JavaScript 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44270369/