# LeetCode Shortest Unsorted Continuous Subarray

LeetCode 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) {
vector<int> nums_copy = nums;
sort(nums_copy.begin(), nums_copy.end());
int i = 0, j = nums.size() - 1;
while (i <= j&&nums[i] == nums_copy[i])++i;
while (j >= i&&nums[j] == nums_copy[j])--j;
return j - i + 1;
}
};
```

1. 从左往右，如果该数已经在最终排序的位置了，那么该数必须小于等于该数右边的最小值
2. 从右往左，如果该数已经在最终排序的位置了，那么该数必须大于等于该数左边的最大值

```/**
*            /------------\
* nums:  [2, 6, 4, 8, 10, 9, 15]
* minsf:  2  4  4  8   9  9  15
*         <--------------------
* maxsf:  2  6  6  8  10 10  15
*         -------------------->
*/
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
vector<int> min_so_far(n, 0), max_so_far(n, 0);
for (int i = 0, maxsf = INT_MIN; i < n; ++i)max_so_far[i] = maxsf = max(maxsf, nums[i]);
for (int i = n - 1, minsf = INT_MAX; i >= 0; --i)min_so_far[i] = minsf = min(minsf, nums[i]);
int i = 0, j = n - 1;
while (i <= j&&nums[i] <= min_so_far[i])++i;
while (j >= i&&nums[j] >= max_so_far[j])--j;
return j - i + 1;
}
};
```