LeetCode-581. Shortest Unsorted Continuous Subarray

来源:互联网 发布:网络的宣传语 编辑:程序博客网 时间:2024/06/05 19:29

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:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.

思路

  1. 从前往后遍历数组,如果出现了后面小于前面元素的情况,则说明需要重新排序的子数组存在,记录下最小的那个数。
  2. 从后往前遍历数组,如果出现前面元素大于后面的元素,记录下最大的那个数。
  3. 从前往后遍历数组,记录下遇到的第一个比之前记录的最小数字大的数的下标a。
  4. 从后往前遍历数组,记录下遇到的第一个比之前记录的最大数字小的数的下标b。
  5. 返回长度,即b-a+1。

Java实现

class Solution {    public int findUnsortedSubarray(int[] nums) {        int lo=0,hi=0;        int min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;        for(int i=0;i<nums.length-1;++i)        {            if(nums[i]>nums[i+1])                min=Math.min(nums[i+1],min);        }        for(int i=nums.length-1;i>0;--i)        {            if(nums[i-1]>nums[i])            max=Math.max(nums[i-1],max);        }        for(int i=0;i<nums.length;++i)        {            if(nums[i]>min)            {                lo=i;                break;            }        }        for(int i=nums.length-1;i>=0;--i)        {            if(nums[i]<max)            {                hi=i;                break;            }        }        return (lo==0&&hi==0)?0:hi-lo+1;    }}
阅读全文
0 0