没什么思路啊,题目如下
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.
[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.
有个思路:2层循环,第一循环移除元素,第二层循环判断移除这个元素后是否有自增序列。
提供一個思路
作出逐差數組: 如 a=[1,3,2,1],逐差後得 [2,-1,-1]
所謂刪除一個元素,即在逐差數組中去頭或去尾,或把相鄰兩個相加合併成一個元素。
因此,若逐差數組中有多於一個負數,則不行; 若無負數,則可以; 否則對惟一的負數作以上操作,若其能被刪除或被合併成正數,則可以
這樣一來,時間複雜度可以降到 O(n)
可以在
O(n)
時間做到:對每個相鄰的
[a, b]
,判断是否a >= b
。這樣的數對破壞嚴格遞增性。如果這樣的數對超過一個,則回傳false。如果一個也沒有,回傳true。如果1中只有一對
[a0, b0]
,判断 "移除a0
或b0
後是否還是遞增" 並返回結果是對的,但是超過規定的時間了,有更好的方法嗎?
時間複雜度為O(n)的方法
這個是不是統計逆序數的個數?