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.
Answer
Original
Code
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intfindUnsortedSubarray(vector<int>& nums){ vector<int> sorted(nums.cbegin(), nums.cend()); sort(nums.begin(), nums.end()); unsigned left = 0, right = nums.size() - 1; for(; left != nums.size() && sorted[left] == nums[left]; ++left) {} while(left <= right && sorted[right] == nums[right]) --right; return right - left + 1; } };