581. Shortest Unsorted Continuous Subarray

来源:互联网 发布:淘宝形象模特 编辑:程序博客网 时间:2024/05/01 15:46

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: 5Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

code:

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        res=[]
        nums2=sorted(nums)
        if nums2==nums:return 0
        for i in range(len(nums)):
            if nums[i]!=nums2[i]:
                res.append(i)
                
        return max(res)-min(res)+1
                

原创粉丝点击