581 Shortest Unsorted Continuous Subarray

1. Question

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 theshortestsuch subarray and output its length.
Example 1:
1
Input: [2, 6, 4, 8, 10, 9, 15]
2
3
Output: 5
4
5
Explanation:
6
You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Copied!
Note:
  1. 1.
    Then length of the input array is in range [1, 10,000].
  2. 2.
    The input array may contain duplicates, so ascending order here means <=.

2. Implementation

(1) Monotone Stack
1
class Solution {
2
public int findUnsortedSubarray(int[] nums) {
3
if (nums == null || nums.length <= 1) {
4
return 0;
5
}
6
7
Stack<Integer> stack = new Stack<>();
8
int n = nums.length;
9
int left = n - 1;
10
11
for (int i = 0; i < n; i++) {
12
while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) {
13
left = Math.min(left, stack.pop());
14
}
15
stack.push(i);
16
}
17
18
stack.clear();
19
20
int right = 0;
21
for (int i = n - 1; i >= 0; i--) {
22
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
23
right = Math.max(right, stack.pop());
24
}
25
stack.push(i);
26
}
27
28
return right - left >= 1 ? right - left + 1 : 0;
29
}
30
}
Copied!

3. Time & Space Complexity

Monotone Stack: 时间复杂度O(n), 空间复杂度O(n)