LeetCode 1574 删除最短子数组使剩余数组有序
🟠 中等偏上
https://leetcode.cn/problems/shortest-subarray-to-be-removed-to-make-array-sorted/description/
思路:
首先删除的是子数组,那么剩下的两端一定是有序的,那么可以先从两端找到两个有序数组,再在这两个数组内滑动即可。
不要忘了可能不要左边或不要右边的情况。
class Solution {
public:
int findLengthOfShortestSubarray(vector<int>& arr) {
int left = 0;
while(left<arr.size()-1&&arr[left]<=arr[left+1]) left++;
// cout<<"left"<<left<<endl;
int right = arr.size()-1;
while(right>0&&arr[right]>=arr[right-1]) right--;
// cout<<"right"<<right<<endl;
if(left>=right) return 0;
int res = min(static_cast<int>(arr.size())-left-1,right);
for(int i = 0;i<=left;i++){
while(right<arr.size()&&arr[i]>arr[right]){
// cout<<i<<right<<endl;
right++;
}
res = min(res,right-i+1-2);
}
return res;
}
};