Skip to content

Commit d8d7d49

Browse files
committed
Shortest Unsorted Continuous Subarray
1 parent f5ce16f commit d8d7d49

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
3+
4+
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order,
5+
then the whole array will be sorted in ascending order, too.
6+
You need to find the shortest such subarray and output its length.
7+
8+
Example 1:
9+
Input: [2, 6, 4, 8, 10, 9, 15]
10+
Output: 5
11+
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
12+
13+
Note:
14+
Then length of the input array is in range [1, 10,000].
15+
The input array may contain duplicates, so ascending order here means <=.
16+
"""
17+
class Solution(object):
18+
def findUnsortedSubarray(self, nums):
19+
"""
20+
:type nums: List[int]
21+
:rtype: int
22+
"""
23+
minimum = float('inf')
24+
maximum = -float('inf')
25+
for i in range(1,len(nums)):
26+
if nums[i] < nums[i-1]:
27+
minimum = min(nums[i],minimum)
28+
maximum = max(nums[i-1], maximum)
29+
if minimum == float('inf'):
30+
return 0
31+
for i in range(len(nums)):
32+
if nums[i] > minimum:
33+
left = i
34+
break
35+
for i in range(len(nums)-1, -1, -1):
36+
if nums[i] < maximum:
37+
right = i
38+
break
39+
return right - left + 1

0 commit comments

Comments
 (0)