我在下面遇到了算法问题:
"给定一个整数序列作为数组,通过从数组中删除不超过一个元素来确定是否可以获得严格增加的序列。
实施例
对于sequence = [1,3,2,1],输出应为 almostIncreasingSequence(sequence)= false;
为了获得严格增加的序列,此数组中没有一个元素可以删除。
对于sequence = [1,3,2],输出应为 almostIncreasingSequence(sequence)= true。
您可以从数组中删除3以获得严格增加的序列[1,2]。或者,您可以删除2以获得严格增加的序列[1,3]。"
我的代码(对于Javascript)是:
function almostIncreasingSequence(sequence) {
var count =0;
for (i =0 ; i<sequence.length-1 ; i++){
if (sequence[i+1]<=sequence[i]){
count++;
}
}
return count <2;
}
但是如果在序列= [1,2,3,4,3,4,5]的情况下 我的代码错了;
请向我解释一个可用于解决此问题的算法。 并且请逐步解释,以便我能理解。
很抱歉不清楚,因为这是我的第一个问题。
答案 0 :(得分:0)
这可能有所帮助。
function almostIncreasingSequence(sequence) {
var exists = false; // Assume the sequence returns false by default
var mainSequence = sequence.slice(); // Clone sequence so that we can use it again
m_seq: // The name of the first loop, so that we can exit from it
for (var i = 0; i < mainSequence.length; i++) { // Loop through the array
sequence.splice(i,1); // Remove an item from the array
s_seq: // The name of the loop, so that we can exit from it
for (var j = 0; j < mainSequence.length-1; j++) { // Loop through sliced array, to find an increasing sequence
if (sequence[j+1] <= sequence[j]) { // Check if next is smaller
exists = false; // if so define false
break s_seq; // exit from the loop
}
exists = true; // if the loop has not been interrupted, return true
}
sequence = mainSequence.slice(); // Reassign the main sequence to be used again.
//console.log('s',mainSequence);
if (exists) {break m_seq;} // İf condition is met, why bother to stay in the loop???
}
return exists;
}
var testing = [1,2,3,4,3,4,5];
var testingAgain = [1,2,3,4,3,7,9];
var testingFinal = [1,1];
// almostIncreasingSequence(testing);
console.log(almostIncreasingSequence(testing));
console.log(almostIncreasingSequence(testingAgain));
console.log(almostIncreasingSequence(testingFinal));
&#13;