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 <=.
题目含义:这道题是要找出最短的子数组,将此子数组按照升序排列以后,整个数组就符合升序排列了。
思路一:先用一个数组temp保存nums,然后对temp排序,然后用两个变量start和end去找两个数组出现不同之处的第一个位置和最后一个位置,最后返回end-start+1就是要找的数组长度
1 public int findUnsortedSubarray(int[] nums) { 2 int n = nums.length; 3 int[] temp = new int[n]; 4 Arrays.copyOfRange(nums,0,nums.length-1); 5 Arrays.sort(temp); 6 int start = 0; 7 while (start < n && nums[start] == temp[start]) start++; 8 int end = n - 1; 9 while (end > start && nums[end] == temp[end]) end--; 10 return end - start + 1; 11 }
方法二:
从前开始往后遍历,找到开始位置,从后往前遍历,找到结束位置,最后返回区间。
以 0,1,2,5,4,3,6,7为例,最终end=5,begin=3
1 public int findUnsortedSubarray(int[] nums) { 2 int n = nums.length, beg = -1, end = -2, min = nums[n-1], max = nums[0]; 3 for (int i=1;i<n;i++) { 4 max = Math.max(max, nums[i]); 5 min = Math.min(min, nums[n-1-i]); 6 if (nums[i] < max) end = i; 7 if (nums[n-1-i] > min) beg = n-1-i; 8 } 9 return end - beg + 1; 10 }