原題是:
Given an integer array, 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, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [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.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
思路:
這個(gè)題需要思路宏觀一點(diǎn)。
用兩個(gè)指針?lè)謩e從數(shù)組的開(kāi)頭和末尾開(kāi)始,與該數(shù)組排序好的版本逐個(gè)元素進(jìn)行比較煎楣。
記錄元素不同的第一個(gè)i份蝴,第一個(gè)j。
i,j 的距離就是所求的需要調(diào)整順序最小子數(shù)組但校。
注意,i,j可能彼此“穿越”,所以只有當(dāng)結(jié)果是大于0的時(shí)候才是所需結(jié)果步鉴。如果小于等于0,說(shuō)明數(shù)組完全不需要調(diào)整任何子數(shù)列的升序璃哟,返回0.
代碼是:
class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
sort = sorted(nums)
i = 0
j = -1
while i < len(nums):
if nums[i] != sort[i]:
break
else:
i += 1
while j >= -len(nums):
if nums[j] != sort[j]:
break
else:
j -=1
ans = len(nums) - i + j +1
return ans if ans >0 else 0