581. Shortest Unsorted Continuous Subarray

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

 

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

 

Constraints:

  • 1 <= nums.length <= 104
  • -105 <= nums[i] <= 105
class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int l = 0, r = nums.length - 1, n = nums.length;
        
        while((l + 1) < n && nums[l] < nums[l + 1]) l++;
        while((r - 1) >= 0 && nums[r] >= nums[r - 1]) r--;
        
        return r - l > 0 ? r - l + 1 : 0;
    }
}

首先想到从左右两边开始看到哪一位违反了rule,然后 r - l + 1.

但是不能这么简单的做判断,因为有【1,2,3,3,3】或者【1,3,2,2,2】这种情况。前者和后者对于终止条件判断是不一样的,前者不需要r前移,而后者需要。所以要考虑别的方法,。

思考过程:从左往右如果当前数小于之前最大的数,说明起码从这里开始就要sort了,然后设这里为右终点r,因为我们还要往后比较,r越来越大

相对的,从右往左如果当前数大于之前最小的数,说明也要至少从这里开始sort。设这里为左终点l,l往前越来越小

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int l = -1, r = -1, n = nums.length;
        int curmax = Integer.MIN_VALUE;
        int curmin = Integer.MAX_VALUE;
        for(int i = 0; i < n; i++) {
            curmax = Math.max(curmax, nums[i]);
            curmin = Math.min(curmin, nums[n - i - 1]);
            
            if(nums[i] < curmax) r = i;
            if(nums[n - i - 1] > curmin) l = n - 1 - i;
        }
        
        return l == -1 ? 0 : r - l + 1;
    }
}

 

posted @ 2021-02-26 01:12  Schwifty  阅读(33)  评论(0编辑  收藏  举报