Leetcode之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.

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<=.

示例:

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.

思路分析:翻译一下题目说的意思,题目说的是我们找到这样一个子数组,只要把它们按照升序排列,那么我们整个数组都能得到一个升序序列了。我们在这采用两个指针,一个start,一个end,用它们来表示需要排成升序序列的子数组的首末。另外我们还设定了一个max,表示从左往右的最大值;一个min,表示从右往左的最小值。如果当前的这个数比最大值要小,比如上面的4 < 6,说明4没有处在升序子序列中,将它标记成end,为啥是end而不是start,因为start最终会跑到前面来,而end会跑到最后面去。对称地,我们找到nums[n - i]中比最小值min要大的值,比如后面的10 > 9,这肯定是不满足升序的。以此类推,没遍历一个元素,我们就会更新最大值max,最小值min以及两个索引start和end,直到所有元素遍历完为止,最后的结果为end - start + 1。

代码:






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值