Shortest Unsorted Continuous Subarray

2017/12/1 posted in  leetcode

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.

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> sortNums = nums;
        sort(sortNums.begin(), sortNums.end());
        int str = 0,end = nums.size()-1;
        while (nums[str]==sortNums[str]) {
            if (str==end) {
                return 0;
            }
            str++;
        }
        while (nums[end]==sortNums[end]) {
            end--;
        }
        return end-str+1;
    }
};