標籤:ISE color div tin pre des his alt ble
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
[execution time limit] 0.5 seconds (cpp)
[input] array.integer sequence
Guaranteed constraints:
2 ≤ sequence.length ≤ 105,
-105 ≤ sequence[i] ≤ 105.
[output] boolean
- Return
true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.
C++解法:
1 bool isSequence(vector<int> sequence) 2 { 3 set<int>iset; 4 for(auto e: sequence) 5 iset.insert(e); 6 if(iset.size() != sequence.size()) //如果sequence中有重複元素,返回false 7 return false; 8 9 vector<int>v = sequence; //如果sequence與排序後的v相等,則說明sequence是遞增有序的10 sort(v.begin(), v.end());11 if(sequence == v)12 return true;13 else14 return false;15 16 }17 18 bool almostIncreasingSequence(std::vector<int> sequence) 19 {20 if (isSequence(sequence))21 return true;22 int i = 0;23 while (i < sequence.size())24 {25 vector<int> v = sequence;26 v.erase(v.begin() + i);27 if(isSequence(v))28 return true;29 ++i;30 }31 return false;32 }
CodeSignal 刷題 —— almostIncreasingSequence