581. 最短无序连续子数组
思路:中间是无序数组,那么除去中间数组之外,左右两边必定是有序数组。
无序数组中最大的值,必定小于其右侧数组最小值
无序数组中最小的值,必定大于其左侧数组最大值
/**
* 581. 最短无序连续子数组
*/
public class Solution581 {
public int findUnsortedSubarray(int[] nums) {
int length = nums.length;
int maxn = Integer.MIN_VALUE, reight = -1;
int minn = Integer.MAX_VALUE, left = -1;
for (int i = 0; i < length; i++) {
if (maxn > nums[i]) {
// 从左到右找, 无序数组中最大的值 必定小于 在其右侧的值
reight = i;
} else {
// 记录最大值
maxn = nums[i];
}
if (minn < nums[length - i - 1]) {
// 从左到右找, 无序数组中最小的值 必定大于 在其右侧的值
left = length - i - 1;
} else {
// 记录最小值
minn = nums[length - i - 1];
}
}
return reight == left ? 0 : reight - left + 1;
}
public static void main(String[] args) {
Solution581 solution581 = new Solution581();
System.out.println(solution581.findUnsortedSubarray(new int[]{1,2,4,5,3}));
System.out.println(solution581.findUnsortedSubarray(new int[]{2,3,3,2,4}));
System.out.println(solution581.findUnsortedSubarray(new int[]{2,6,4,8,10,9,15}));
System.out.println(solution581.findUnsortedSubarray(new int[]{1,2,3,4,5,6,7}));
System.out.println(solution581.findUnsortedSubarray(new int[]{1,2}));
System.out.println(solution581.findUnsortedSubarray(new int[]{2,1}));
System.out.println(solution581.findUnsortedSubarray(new int[]{1,3,3,3,2}));
}
}