题目链接: https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray
难度:简单
通过率:32.8%
题目描述:
给定一个整数数组,你需要寻找一个 连续的子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是 最短 的,请输出它的长度。
示例:
示例 1:
**输入:** [2, 6, 4, 8, 10, 9, 15]
**输出:** 5
**解释:** 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :
- 输入的数组长度范围在 [1, 10,000]。
- 输入的数组可能包含 重复 元素 ,所以 升序 的意思是 < =。
思路:
排序比较即可!
代码:
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sort_nums = sorted(nums)
left = 0
right = len(nums) - 1
while left <= right and nums[left] == sort_nums[left]:
left += 1
while left <= right and nums[right] == sort_nums[right]:
right -= 1
return right - left + 1