LeetCode 1574 Shortest Subarray to be Removed to Make Array Sorted (两点法 + 二分)

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.

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值