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.

思路:
第一遍从左往右扫,看当前值是否比找到的最大值还小,如果是这样的话,明显中间不是递增的。同样,从右往左扫,如果当前值比已经找到的最小值大,那么中间部分也不是递增的。
 1 class Solution {
 2     public int findUnsortedSubarray(int[] nums) {
 3         if (nums == null || nums.length == 0 || nums.length == 1) return 0;
 4         int max = Integer.MIN_VALUE, end = -1;
 5         // iterate from beginning of array find the last element which is smaller than
 6         // the last seen max from its left side and mark it as end
 7         for (int i = 0; i < nums.length; i++) {
 8             max = Math.max(max, nums[i]);
 9             if (nums[i] < max)
10                 end = i;
11         }
12         if (end == -1) return 0;
13 
14         int min = Integer.MAX_VALUE, begin = -1;
15         for (int i = nums.length - 1; i >= 0; i--) {
16             min = Math.min(min, nums[i]);
17             if (nums[i] > min)
18                 begin = i;
19         }
20         return end - begin + 1;
21     }
22 }

猜你喜欢

转载自www.cnblogs.com/beiyeqingteng/p/11371269.html