Skip to content

Commit 8d65383

Browse files
authored
Update 0581-最短无序连续子数组.py
1 parent ec0d01a commit 8d65383

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed
Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
1-
class Solution(object):
2-
def findUnsortedSubarray(self, nums):
3-
"""
4-
:type nums: List[int]
5-
:rtype: int
6-
"""
7-
s = sorted(nums)
8-
if s == nums:
9-
return 0
10-
for i in range(len(s)):
11-
if s[i] != nums[i]:
12-
break
13-
for j in range(len(s) - 1, -1, -1):
14-
if s[j] != nums[j]:
15-
break
16-
# print i, j
17-
# print s, nums
18-
return len(s) - i - (len(s) - 1 -j)
19-
1+
# 很自然的想法,将原数组copy并排序,和原数组比对。
2+
3+
class Solution:
4+
def findUnsortedSubarray(self, nums: List[int]) -> int:
5+
nums_copy=nums[:]
6+
nums_copy.sort()
7+
left=float("inf")
8+
right=0
9+
for i in range(len(nums)):
10+
if(nums_copy[i]!=nums[i]):
11+
left=min(left,i)
12+
right=max(right,i)
13+
return right-left+1 if(right-left+1 > 0) else 0
14+
15+
作者吴彦祖
16+
链接https://leetcode.cn/problems/shortest-unsorted-continuous-subarray/solutions/45188/liang-ci-bian-li-pai-xu-bi-dui-python3-by-zhu_shi_/
17+
来源力扣LeetCode
18+
著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处

0 commit comments

Comments
 (0)