LeetCode581: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.

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:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

LeetCode:链接

题目的意思是输入一个数组,这个数组可能是排序好的,也可能是乱序的。如果数组是乱序的,我们就要找出这个数组的最小子数组,以满足,只要排序好这个子数字,整个数字就是有序的。

  • 大体思路是这样的:如果当前元素比它前面的元素中的最大的值小,那它就在待排序的子数组里;如果当前元素比它后面元素中的最小值要大,那它也需要包含在待排序的子数组里
  • 我们用一个变量(max)来保存遍历过的元素中的最大值,用一个变量(min)来保存从数组尾部遍历的元素中的最小值。
  • 然后我们只要通过遍历找到,最后一位待排序元素和最前面的待排序元素就可以了。
class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_value = nums[0]
        min_value = nums[-1]
        length = len(nums)
        '''如果不需要调整 end-start+1就是0'''
        end, start = -2, -1
        for i in range(1, length):
            max_value = max(nums[i], max_value)
            min_value = min(nums[length-i-1], min_value)

            if nums[i] < max_value:
                end = i
            if nums[length-i-1] > min_value:
                start = length-i-1
        return end - start + 1

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84964685