欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[LeetCode] 581. Shortest Unsorted Continuous Subarray

程序员文章站 2024-02-24 15:09:54
...

题目内容

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.

题目思路

这道题目可以先获得一个正确的进行比较。需要确定两个变量,第一个是左侧变量,第二个是持续到最右侧的位置的变量,取最大值。也就是当遇到第一个的时候,同时改变两个变量。然后依次向后遍历,知道末尾为止,如果遇到不等就改变第二变量的数值


程序代码

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        tnums=sorted(nums)
        left,right=-1,-1
        for i in range(len(nums)):
            if nums[i]!=tnums[i]:
                if left==-1:
                    left=i
                right=i
        return right-left+1 if right!=left else 0