581. Shortest Unsorted Continuous Subarray
程序员文章站
2022-03-07 18:28:01
...
1,题目要求
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.
找到一个连续的子数组,如果你只按升序对这个子数组进行排序,那么整个数组也将按照升序排序。
2,题目思路
对这样的一个需要排序的一个子数组,它的特性又是什么?
通过分析和观察,可以发现,在这样的子数组中,最小值大于子数组前面中的数组的最大值;
最大值小于后面数组中的数组的最小值。
因此,分别需要两个变量来记录这样的最大值和最小值,另外需要两个变量来记录满足条件的子数组的起始位置和结束位置。
3,程序源码
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size(), minVal = nums[n-1], maxVal = nums[0], start = -1, end = -2;
for(int i = 1;i<n;i++)
{
maxVal = max(maxVal, nums[i]);
minVal = min(minVal, nums[n-i-1]);
if(nums[i] < maxVal) end = i;
if(nums[n-i-1] > minVal) start = n-1-i;
}
return end - start + 1;
}
};
推荐阅读
-
# 189. Rotate Array # 581. Shortest Unsorted Continuous Subarray
-
LeetCode 581. Shortest Unsorted Contimuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
leetcode(581):Shortest Unsorted Continuous Subarray
-
[LeetCode]581. Shortest Unsorted Continuous Subarray
-
【时间复杂度优化】LeetCode 581. Shortest Unsorted Continuous Subarray
-
Leetcode 581. Shortest Unsorted Continuous Subarray