# 581. Shortest Unsorted Continuous Subarray

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.
``````

Note:

1. Then length of the input array is in range [1, 10,000].
2. The input array may contain duplicates, so ascending order here means <=.

``````class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int res = 0, start = -1, n = nums.size();
for (int i = 1; i < n; ++i) {
if (nums[i] < nums[i - 1]) {
int j = i;
while (j > 0 && nums[j] < nums[j - 1]) {
swap(nums[j], nums[j - 1]);
--j;
}
if (start == -1 || start > j) start = j;
res = i - start + 1;
}
}
return res;
}
};
``````

``````class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size(), i = 0, j = n - 1;
vector<int> t = nums;
sort(t.begin(), t.end());
while (i < n && nums[i] == t[i]) ++i;
while (j > i && nums[j] == t[j]) --j;
return j - i + 1;
}
};
``````

``````class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size(), start = -1, end = -2;
int mn = nums[n - 1], mx = nums[0];
for (int i = 1; i < n; ++i) {
mx = max(mx, nums[i]);
mn = min(mn, nums[n - 1 - i]);
if (mx > nums[i]) end = i;
if (mn < nums[n - 1 - i]) start = n - 1 - i;
}
return end - start + 1;
}
};
``````

https://leetcode.com/problems/shortest-unsorted-continuous-subarray/

https://leetcode.com/problems/shortest-unsorted-continuous-subarray/discuss/103057/java-on-time-o1-space

https://leetcode.com/problems/shortest-unsorted-continuous-subarray/discuss/103062/c-clean-code-2-solution-sort-onlgn-max-min-vectors-on

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation