Shortest Unsorted Continuous Subarray

Leave a comment

May 25, 2017 by oneOokay

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

我想到的偷懒解法就是复制一下原array, 再sort array.然后两个array对比,左右找到第一个不同的元素的index就可以得出一个subarray了.

最赞超级妙.就画一个图就可以. 会是一个曲折的曲线.

  • End点在于:最后一个谷底点.
  • Start点在于:第一个的顶峰.

代码也很妙: 在一个for-loop里面同时进行从左往右找谷底和从右往左找顶峰.

public int findUnsortedSubarray(int[] nums) {
        int len=nums.length;
        int max=Integer.MIN_VALUE, min=Integer.MAX_VALUE;
        int start=-1, end=-1;
        for(int i=0; i<len; i++){
            max = Math.max(max, nums[i]); 
            min = Math.min(min, nums[len-i-1]);
//当前的值,小于最大值,说明是下降的,可能是谷底,update end为当前的index
            if(nums[i] < max) end = i;
//当前的值,大于最小值,说明是上升的,可能是顶峰,update start为当前的index
            if(nums[len-i-1] > min) start = len-i-1;
        }
        //特殊情况
        if(start==-1) //the entire array is already sorted
            return 0;
        
        return end-start+1;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: