feat(581-shortest-unsorted-continuous-subarray): add py3 solution

This commit is contained in:
Sangeeth Sudheer 2022-04-05 03:45:52 +05:30
parent 1abc610390
commit ee2167f554
2 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,29 @@
Given an integer array `nums`, 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.
Return _the shortest such subarray and output its length_.
**Example 1:**
Input: nums = [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.
**Example 2:**
Input: nums = [1,2,3,4]
Output: 0
**Example 3:**
Input: nums = [1]
Output: 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
**Follow up:** Can you solve it in `O(n)` time complexity?

View File

@ -0,0 +1,39 @@
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]