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

题目:删除数组中最小长度的连续子序列,使得剩下的元素按非降顺序排列,求最小长度是多少。

思路:先找前半部分和后半部分的按序排好的长度,然后前半部分往回遍历,用二分法查找大于或等于遍历值的元素位置,更新结果值

代码

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值