Tuesday, February 25, 2020

581. Shortest Unsorted Continuous Subarray (easy)

Q:

Given an integer array, 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, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [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.
Note:
  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.
A:

首先找到左边和右边的不协调的地方。
然后在这个区间,找到最大最小的值。
然后再向两边扩展        (思路挺简单,可是就是写起来有点儿啰嗦)

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size();
        if(n == 0)
            return 0;
        int start = 0, end = n-1;
        // get the first that bigger than next
        bool isSorted = true;
        for(int i =0; i<n-1;++i){
            if(nums[i] > nums[i+1])
            {
                start = i;
                isSorted = false;
                break;
            }
        }
        if(isSorted)
            return 0;
        // count backward, get the first that smaller than previous one
        for(int i =n-1; i>0; --i){
            if(nums[i] < nums[i-1])
            {
                end = i;
                break;
            }
        }
        // get min and max value of that range
        int minn= nums[start]; // inclusive
        int maxx= minn;
        for(int i =start+1; i<=end; i++)
        {
            minn = min(minn, nums[i]);
            maxx = max(maxx, nums[i]);
        }        
        // now shrink        
        for(int i =start-1; i>=-1;--i)
        {
            if(i <0 || nums[i]<=minn)
            {
                start = i+1;
                break;
            }
        }
        for(int i = end+1; i<= n;++i)
        {
            if(i==n || nums[i] >= maxx)
            {
                end=i-1;
                break;
            }
        }
        return end-start +1;
    }
};


Mistakes:
   忘记检查如果全部已经sorted 好了。怎么办

No comments:

Post a Comment