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.
算法一:
排序,然后跟原数组比对,有什么不一样
有几个注意点
- 数组要copy, 用Arrays.copyOf(int[] original,int newLength)
- 如果数组已经是完全排序的,要早点返回
public int findUnsortedSubarray(int[] nums) {
int[] copy = Arrays.copyOf(nums, nums.length);
Arrays.sort(copy);
int res = nums.length;
int i = 0;
while(i < nums.length && copy[i] == nums[i]) {
res--; i++;
}
if(res == 0) return res;
i = nums.length -1;
while(i >= 0 && copy[i] == nums[i]) {
res--; i--;
}
return res;
}
算法2 有点难懂
既然不符合排序规则,那么肯定能找到两边各自的一个突变的点
右边的end这个数, 比它左边的数中最大的要小,它是个突变
(正常来说,右边的数要比左边所有的数都大,比最大的数还大)
一边找,一边更新目前为止最大的值
从左边一直找过来,最后一个不正常的突变的数,就是end
反之从右边找过来,可以找到最后一个不正常的数,在最左边是begin
public int findUnsortedSubarray(int[] nums) {
int max = nums[0];
int end = -1, beg = -1;
for(int i=1;i<nums.length;i++) {
if(nums[i] < max) {
end = i;
}
max = Math.max(max, nums[i]);
}
int min = nums[nums.length-1];
for(int i=nums.length-2;i>=0;i--) {
if(nums[i] > min) {
beg = i;
}
min = Math.min(min, nums[i]);
}
return end == -1 ? 0 : end - beg +1;
}