最短無序連續子數組
給定一個整數數組,你需要尋找一個連續的子數組,如果對這個子數組進行升序排序,那麼整個數組都會變爲升序排序。
你找到的子數組應是最短的,請輸出它的長度。
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sorted_nums = sorted(nums)
start_index, end_index = len(nums), 0
for i in range(len(nums)):
if sorted_nums[i] != nums[i]:
start_index = min(start_index, i)
end_index = max(end_index, i)
else:
pass
if start_index > end_index:
return 0
else:
return end_index - start_index + 1