1. 程式人生 > 實用技巧 >581. Shortest Unsorted Continuous Subarray

581. Shortest Unsorted Continuous Subarray

Given an integer array, you need to find onecontinuous subarraythat if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find theshortestsuch subarray and output its length.

給你一個數組,找一個最短的連續子陣列,對這個子陣列排序,整個陣列就升序

需要從做到右找到第一個大於後面數字的下標l,從右到左找到第一個小於前面數字的下標r

然後再nums[l : r + 1]找到最大值和最小值,然後左邊從l往左找到不大於min的l,右邊從r往右找到不小於max的r,答案就是r - l + 1

這題標成easy不太合適吧

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n < 2:
            return 0
        l 
= 0 r = n - 1 while l + 1 < n and nums[l + 1] >= nums[l]: l += 1 while r >= 1 and nums[r - 1] <= nums[r]: r -= 1 if l > r: return 0 max_v = max(nums[l: r + 1]) min_v = min(nums[l: r + 1]) while l >= 1 and
nums[l - 1] > min_v: l -= 1 while r + 1 < n and nums[r + 1] < max_v: r += 1 return r - l + 1