一、题目说明
题目581. Shortest Unsorted Continuous Subarray,求最大连续子数组(如果该子数组有序,则整个数组有序)的长度。难度是Easy!
二、我的解答
不动脑子,将数组排序,然后从左到右比较,再从右到左比较。即可获得最短子数组的长度。
class Solution{
public:
int findUnsortedSubarray(vector<int>& nums){
int len = nums.size()-1;
vector<int> tmp;
for(int i=0;i<nums.size();i++){
tmp.push_back(nums[i]);
}
sort(tmp.begin(),tmp.end());
int left = 0,right = len;
while(left<len && tmp[left]==nums[left]){
left++;
}
while(right>=left && tmp[right]==nums[right]){
right--;
}
return (right-left+1);
}
};
性能如下:
Runtime: 44 ms, faster than 51.61% of C++ online submissions for Shortest Unsorted Continuous Subarray.
Memory Usage: 11.3 MB, less than 38.10% of C++ online submissions for Shortest Unsorted Continuous Subarray.
三、优化措施
优化如下:
class Solution{
public:
int findUnsortedSubarray(vector<int>& nums){
int m = nums[0], n = nums.back(), l = -1, r = -2;
int len = nums.size();
//从左到右遍历,如果nums[i]比前面的都大,则i+1的位置正确
for (int i = 1; i < len; ++i)
{
m = max(m, nums[i]);
n = min(n, nums[len - 1 - i]);
if (m != nums[i]) r = i;
if (n != nums[len - 1 - i]) l = len - 1 - i;
}
return r - l + 1;
}
};
性能如下:
Runtime: 36 ms, faster than 77.82% of C++ online submissions for Shortest Unsorted Continuous Subarray.
Memory Usage: 10.5 MB, less than 71.43% of C++ online submissions for Shortest Unsorted Continuous Subarray.