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
题目链接:https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/
题目大意:给一个数组,求它的一个长度最小的子数组,删除之后可使原数组单调不减
题目分析:首先分别找首尾满足单调不减的子数组,对某一边遍历,并在另一边二分找满足条件的能使答案尽可能小的位置,比如枚举左侧,就是二分右侧找第一个比当前数字小的位置,这样计算出来的结果是在至少从左侧选一个数的情况下得出的解,还需要加上只从右侧选的情况。有两个小优化,一是如果左侧和右侧有重叠则原数组必然已满足条件,二是对一侧枚举时可以提前结束循环,以枚举左侧为例,倒叙枚举,假设枚举到i时求得的right pos恰好等于右侧单调不减的子数组的首位置,因为左侧也是单调不减的,i-1位置只会更小,因此可以直接结束循环
2ms,时间击败75%
class Solution {
int bsearch(int[] arr, int st, int ed, int x) {
int l = st, r = ed, ans = arr.length, mid = 0;
while (l <= r) {
mid = (l + r) >> 1;
if (arr[mid] >= x) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
public int findLengthOfShortestSubarray(int[] arr) {
int n = arr.length;
if (n == 1) {
return 0;
}
int l = 0, r = n - 1;
while (l + 1 < n && arr[l] <= arr[l + 1]) {
l++;
}
while (r - 1 >= 0 && arr[r] >= arr[r - 1]) {
r--;
}
if (l >= r) {
return 0;
}
int ans = n;
for (int i = l; i >= 0; i--) {
int rPos = bsearch(arr, r, n - 1, arr[i]);
// System.out.println("i = " + i + " rpos = " + rPos);
ans = Math.min(ans, rPos - i - 1);
if (rPos == r) {
break;
}
}
ans = Math.min(ans, r);
return ans;
}
}