leetcode/0581_shortest-unsorted-continuous-subarray/python3/solution.py

40 lines
1.2 KiB
Python

class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
min_unsorted = float("inf")
max_unsorted = float("-inf")
# Find min and max element in the unsorted portion
for i, num in enumerate(nums):
if not self.is_sorted(i, nums):
min_unsorted = min(min_unsorted, num)
max_unsorted = max(max_unsorted, num)
if min_unsorted == float("inf"):
return 0
# Find right places for min and max elements from previous
# step in the "sorted" section of the array
left = 0
while nums[left] <= min_unsorted:
left += 1
right = len(nums) - 1
while nums[right] >= max_unsorted:
right -= 1
return right - left + 1
def is_sorted(self, i: int, nums: List[int]) -> bool:
n = len(nums)
if n <= 1:
return True
if i == 0:
return nums[i] <= nums[i + 1]
if i == n - 1:
return nums[i - 1] <= nums[i]
return nums[i - 1] <= nums[i] <= nums[i + 1]