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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值