# LeetCode 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 <=.

### Method one

Code

class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
_len, _sorted = len(nums), sorted(nums)
if nums == _sorted:
return 0
start_index  = min([index for index in range(_len) if nums[index] != _sorted[index]])
end_index  = max([index for index in range(_len) if nums[index] != _sorted[index]])
return end_index - start_index + 1



C++ Version

class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int length = nums.size();
auto sorted_nums = nums;
sort(sorted_nums.begin(), sorted_nums.end());
int start_index = length, end_index = 0;
for (int index = 0; index < length; ++index){
if (nums[index] != sorted_nums[index]){
start_index = min(start_index, index);
end_index = max(end_index, index);
}

}
return end_index >= start_index? end_index - start_index + 1: 0;
}
};


## Note

• Python版的列表生成式很巧妙，要注意掌握！！
start_index  = min([index for index in range(_len) if nums[index] != _sorted[index]])
end_index  = max([index for index in range(_len) if nums[index] != _sorted[index]])

• C++ 版的列表复制也要注意：auto sorted_nums = nums;以及排序算法sort(sorted_nums.begin(), sorted_nums.end());