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:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> sorted(nums);
        sort(sorted.begin(),sorted.end());
        int n = nums.size();
        int i = 0,j = n - 1;
        //排序前[2, 6, 4, 8, 10, 9, 15]
        //排序后[2, 4, 6, 8, 9, 10, 15]
        //从前往后找到第一个不同的下标,从后往前找到第一个不同的,中间部分就是需要调整的
        for(i = 0;i < n;i++)
        {
            if(nums[i] != sorted[i])
                break;
        }
        
        for(j = n-1;j > i;j--)
        {
            if(nums[j] != sorted[j])
                break;
        }
        
        return j - i + 1;
    }
};

另一种高效解法,时间复杂度O(n),空间复杂度O(n),解法如下:

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size();
        vector<int> minl(n);
        vector<int> maxr(n);
        for(int i = n-1,min_val=INT_MAX;i >= 0;i--)
            minl[i] = min_val = min(min_val,nums[i]);
        
        for(int j = 0,max_val=INT_MIN;j < n;j++)
            maxr[j] = max_val = max(max_val,nums[j]);

        int i = 0, j = n - 1;
        while (i < n && nums[i] <= minl[i]) i++;
        while (j > i && nums[j] >= maxr[j]) j--;
        
        return j - i + 1;
    }
};

时间上击败98.68%C++ online submissions,内存上由于使用了两个vector,所以仅击败7.95%

Runtime: 52 ms, faster than 98.68% of C++ online submissions for Shortest Unsorted Continuous Subarray.
Memory Usage: 28.4 MB, less than 7.95% of C++ online submissions for Shortest Unsorted Continuous Subarray.