Description 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 an
Description
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:
Output:
5Explanation:
You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.Note:
分析
题目的意思是:给定一个数组,找出一个连续子数组,如果这个子数组递增,那么整个数组就递增。
- 从前往后寻找最大值,如果遇见元素小于前面的最大值,我们找到右边界;从后往前寻找最小值,如果遇见的元素大于前面的最小值,我们找到左边界。
代码
class Solution {public:
int findUnsortedSubarray(vector<int>& nums) {
int len=nums.size();
int min_value=nums[len-1];
int max_value=nums[0];
int r=-1;
int l=0;
for(int i=0;i<nums.size();i++){
max_value=max(nums[i],max_value);
if(nums[i]<max_value){
r=i;
}
min_value=min(nums[len-1-i],min_value);
if(nums[len-1-i]>min_value){
l=len-1-i;
}
}
return r-l+1;
}
};
参考文献
581. Shortest Unsorted Continuous Subarray