581. Shortest Unsorted Continuous Subarray

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int findUnsortedSubarray(int[] nums) {
// [2, 6, 4, 8, 10, 9, 15]
// [6, 4, 8, 10, 9]

// [1, 3, 2, 2, 2]
// [2, 2, 2, 3]

// [1, 2, 3]
// [1, 2, 3]

int[] sortedNums = nums.clone();
Arrays.sort(sortedNums);

int i = 0, j = nums.length - 1;
while (i <= j && nums[i] == sortedNums[i]) {
i++;
}
while (i <= j && nums[j] == sortedNums[j]) {
j--;
}

return j - i + 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public int findUnsortedSubarray(int[] nums) {
// [2, 16, 4, 0, 10, 9, 15]
// [2, 16, 4, 0, 10, 9, 15]

// [1, 3, 2, 2, 2]
// [2, 2, 2, 3]

// [1, 2, 3]
// [1, 2, 3]

int left = 0, right = -1;
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

for (int i = 0; i < nums.length; i++) {
if (nums[i] < max) {
// nums[i] 比左侧的最大值小,nums[i] 必须纳入子数组
right = i;
} else {
max = nums[i];
}
if (nums[nums.length - 1 - i] > min) {
// nums[nums.length - 1 - i] 比右侧的最小值大,nums[nums.length - 1 - i] 必须纳入子数组
left = nums.length - 1 - i;
} else {
min = nums[nums.length - 1 - i];
}
}

return right - left + 1;
}
}

Reference

581. Shortest Unsorted Continuous Subarray