Given an integer array arr
, remove a subarray (can be empty) from arr
such that the remaining elements in arr
are non-decreasing.
Return the length of the shortest subarray to remove.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted. Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1] Output: 4 Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3] Output: 0 Explanation: The array is already non-decreasing. We do not need to remove any elements.
Constraints:
1 <= arr.length <= 105
0 <= arr[i] <= 109
题目:删除数组中最小长度的连续子序列,使得剩下的元素按非降顺序排列,求最小长度是多少。
思路:先找前半部分和后半部分的按序排好的长度,然后前半部分往回遍历,用二分法查找大于或等于遍历值的元素位置,更新结果值
代码
class Solution {
public:
int findLengthOfShortestSubarray(vector<int>& arr) {
int i = 0, j = arr.size()-1, res = arr.size();
while(i < arr.size()-1 && arr[i] <= arr[i+1]) i++;
while(j > i && arr[j-1] <= arr[j]) j--;
if(j == i) return 0;
for(int i1 = i; i1 >= 0; i1--){
int p = lower_bound(arr.begin()+j, arr.end(), arr[i1]) - arr.begin();
if(p < 0) p = arr.size();
res = min(res, p-i1-1);
}
return min(res, j);
}
};
time: O(N*logN), space:O(1)
PS:c++的lower_bound和upper_bound太好用了,用的我好像自己都不会写二分法了T_T