双指针,将该数组于排序后的数组比较,找到两个位置开始不同的位置,然后做差即可求出长度。
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sortNums = sorted(nums)
if sortNums == nums:
return 0
for i in range(len(nums)):
if nums[i] != sortNums[i]:
break
for j in range(len(nums)-1, -1, -1):
if nums[j] != sortNums[j]:
break
return j - i + 1
感觉用 while 比用 for 好一些!!!
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sortedNums = sorted(nums)
i, j = 0, len(nums) - 1
while i <= j and nums[i] == sortedNums[i]:
i += 1
while i <= j and nums[j] == sortedNums[j]:
j -= 1
return j - i + 1
网友评论