Leetcode之Shortest Unsorted Continuous Subarray 问题

来源:互联网 发布:古埃及人知乎 编辑:程序博客网 时间:2024/06/05 06:34

问题描述:

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
原创粉丝点击