Skip to content

Commit dd9900b

Browse files
committed
Add 581
1 parent ccc5e59 commit dd9900b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@
150150
| 563 | Binary Tree Tilt | Easy | O(N) | O(H) | Tree, DFS, Recursion | | |
151151
| 567 | Permutation in String | Medium | O(S1 + S2) | O(1) | String, Two Pointers, Sliding Window | | |
152152
| 573 | Squirrel Simulation | Medium | O(N) | O(1) | Premium, Math | | 🔒 |
153+
| 581 | Shortest Unsorted Continuous Subarray | Medium | O(N) | O(1) | Array | | |
153154
| 583 | Delete Operation for Two Strings | Medium | O(N^2) | O(N) | Dynamic Programming, String | | |
154155
| 593 | Valid Square | Medium | O(1) | O(1) | Math | | |
155156
| 605 | Can Place Flowers | Easy | O(N) | O(1) | Array, Greedy | | |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#
2+
# @lc app=leetcode id=581 lang=python3
3+
#
4+
# [581] Shortest Unsorted Continuous Subarray
5+
#
6+
7+
# @lc code=start
8+
# TAGS: Array
9+
class Solution:
10+
# 216 ms, 83 %. O(NlogN)
11+
def findUnsortedSubarray(self, nums: List[int]) -> int:
12+
sorted_nums = sorted(nums)
13+
start = end = -1
14+
for i in range(len(nums)):
15+
if nums[i] != sorted_nums[i]:
16+
if start == -1:
17+
start = i
18+
end = i
19+
return 0 if start == end == -1 else end - start + 1
20+
21+
# 196 ms, 81.96%. Time: O(N). Space: O(1)
22+
def findUnsortedSubarray(self, nums: List[int]) -> int:
23+
# Find right limit of the subarray. Traverse array from left to right
24+
right_ptr = 0
25+
big = nums[0]
26+
for i in range(len(nums)):
27+
if nums[i] < big:
28+
right_ptr = i
29+
else:
30+
big = nums[i]
31+
32+
# Find left limit of the subarray.Traverse array from right to left
33+
left_ptr = 0
34+
small = nums[-1]
35+
for i in reversed(range(len(nums))):
36+
if nums[i] > small:
37+
left_ptr = i
38+
else:
39+
small = nums[i]
40+
41+
if right_ptr == left_ptr: return 0
42+
return right_ptr - left_ptr + 1
43+
44+
# @lc code=end
45+

0 commit comments

Comments
 (0)