581. Shortest Unsorted Continuous Subarray

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.

给你一个数组,找一个最短的连续子数组,对这个子数组排序,整个数组就升序

需要从做到右找到第一个大于后面数字的下标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

 

posted @ 2020-07-15 22:32  whatyouthink  阅读(140)  评论(0编辑  收藏  举报