public class Solution {
public int findUnsortedSubarray(int[] nums) {
if (nums == null || nums.length < 1) return 0;
int len = nums.length;
int start = 0;
int end = 0;
int max = nums[0];
int min = nums[len - 1];
for (int i = 1; i < len; i++) {
max = Math.max(max, nums[i]);
min = Math.min(min, nums[len - 1 - i]);
if (nums[i] < max) {
end = i;
}
if (nums[len - 1 - i] > min) {
start = len - 1 - i;
}
}
return end - start == 0 ? 0 : end - start + 1;
}
}
/*
[2,6,4,8,10,9,15]
[2,6,4,8,16,9,15]
[1,2,3]
[3,2,-100]
[1,2,6,3,5,-1,16,8]
[1,3,2,2,2]
[2,3,3,2,4]
[1,3,1,3,2,4]
[1,2,5,3,4]
*/
// O(N) solution, space O(1)
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int minIndex = nums.length - 1;
int maxIndex = 0;
int i = -1;
int j = -1;
for (int k = nums.length - 1; k >= 0; k--) {
if (nums[k] > nums[minIndex]) {
i = k;
} else {
minIndex = k;
}
}
for (int k = 0; k < nums.length; k++) {
if (nums[k] < nums[maxIndex]) {
j = k;
} else {
maxIndex = k;
}
}
if (j == -1 || i == -1) {
return 0;
}
return j - i + 1;
}
}
/* // N^2 solution
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int i = 0;
int j = nums.length - 1;
boolean min = true;
boolean max = true;
while(i < j) {
min = true;
max = true;
for (int k = 0; k < nums.length; k++) {
int val = nums[k];
if (k > i && val < nums[i]) {
min = false;
}
if (k < j && val > nums[j]) {
max = false;
}
}
if (min) {
i++;
}
if (max) {
j--;
}
if (!min && !max){
break;
}
}
if (min && max) { return 0; }
return j - i + 1;
}
} */