581. shortest disorderly consecutive sub-array
Given an array of integers, you need to look for a consecutive sub-array, if sorted in ascending order of the sub-array, the entire array will become ascending order.
You should find the sub-array is the shortest, please output of its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
output: 5
Explanation: You only need to [6, 4, 8, 10, 9] in ascending order, then the whole table are changed in ascending order.
Description:
Input array length in the range [1, 10,000].
Input array may contain duplicate elements, so ascending mean <=.
class Solution {
public int findUnsortedSubarray(int[] nums) {
if(nums.length == 0 || nums.length == 1 || nums == null) {
return 0;
}
int len = nums.length;
int temp=0;
int left = -1, right = -1;
int max = nums[0], min = nums[len - 1];
for(int i = 1; i < len; i++) {
if (max > nums[i]) {
right = i;
} else {
max = nums[i];
}
temp= len - i - 1;
if (min < nums[temp]) {
left = temp;
} else {
min = nums[temp];
}
}
return right > left ? right - left + 1 : 0;
}
}