Trên codefight có bài tập thế này
Given a sequence of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.
Example
For sequence = [1, 3, 2, 1], the output should be almostIncreasingSequence(sequence) = false;
For sequence = [1, 3, 2], the output should be almostIncreasingSequence(sequence) = true.
Input/Output[time limit] 500ms (cpp)
[input] array.integer sequenceConstraints:
2 ≤ sequence.length ≤ 10^5,
-10^5 ≤ sequence[i] ≤ 10^5.[output] boolean
true if it is possible, false otherwise.
Tạm dịch đề bài: Cho một dãy số bất kì, kiểm tra xem nếu xóa 1 số thuộc dãy số đó thì ta có thu được 1 dãy tăng dần không. Yêu cầu các số trong dãy thu được sau khi xóa phải khác nhau (cái này sau khi xem test case của nó thì em mới biết)
Em làm bài này bằng cách:
- Kiểm tra xem dãy cho trước có phải dãy tăng dần và các phần tử đều khác nhau không, nếu có thì dãy thỏa mãn
- Nếu dãy cho trước không phải tăng dần thì xóa từng phần tử đi rồi kiểm tra dãy thu được xem có tăng dần và có các phần tử khác nhau không. Nếu có thì thỏa mãn.
code của em đây
bool increasingTest(std::vector<int> sequence){
for(int j=0;j<sequence.size()-1;j++){
if(sequence[j]>sequence[j+1]||sequence[j]==sequence[j+1])
{
return false;}
}
return true;
}
bool almostIncreasingSequence(std::vector<int> sequence) {
if(increasingTest(sequence))
{
return true;
}
else
{
std::vector<int>::iterator iter;
for(int i=0;i<sequence.size();i++)
{
iter = sequence.begin()+i;
int temp=sequence[i];
sequence.erase(sequence.begin()+i);
if(increasingTest(sequence))
{
return true;
}
sequence.insert(iter, temp);
}
return false;
}
}
Code của em thỏa mãn tất cả các sample test nhưng lại không thỏa mãn 1 cái hidden test do tốc độ xử lý chậm hơn bài ra. Vậy em muốn hỏi mọi người có thuật toán nào khác nhanh hơn không hoặc giúp em tối ưu code để xử lý nhanh hơn.
Em xin cảm ơn!