题面:
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.
题解:主要思路找出前后两个指针,前一个表示第一个开始不递增的数,后一个表示最后一个不递增的数。换个思路,即将原数组递增排序后,第一个和最后一个不同的数
代码:
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { if(nums.size() < 2) return 0; int res = 0,start= 0,end = 0; vector<int> temp = nums; sort(temp.begin(),temp.end()); for(int i = 0 ; i < nums.size(); i++) { if(nums[i] != temp[i]) { start = i; break; } } for(int i = nums.size()-1 ; i >= 0 ; i--) { if(nums[i] != temp[i]) { end = i; break; } } if(end < start || end == start || start < 0) return 0; res = end -start + 1; return res; } };