-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathShortestUnsortedContinuousSubarray.java
More file actions
83 lines (67 loc) · 2.09 KB
/
ShortestUnsortedContinuousSubarray.java
File metadata and controls
83 lines (67 loc) · 2.09 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package array;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
/**
* Description: https://leetcode.com/problems/shortest-unsorted-continuous-subarray
* Difficulty: Medium
*/
public class ShortestUnsortedContinuousSubarray {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public int findUnsortedSubarrayViaMonotonicStacks(int[] nums) {
int left = nums.length;
int right = 0;
Deque<Integer> stack = new LinkedList<>();
for (int l = 0; l < nums.length; l++) {
while (!stack.isEmpty() && nums[l] < nums[stack.peek()]) {
left = Math.min(left, stack.pop());
}
stack.push(l);
}
stack.clear();
for (int r = nums.length - 1; r >= 0; r--) {
while (!stack.isEmpty() && nums[r] > nums[stack.peek()]) {
right = Math.max(right, stack.pop());
}
stack.push(r);
}
return right - left < 0 ? 0 : right - left + 1;
}
/**
* Time complexity: O(nlog n)
* Space complexity: O(n)
*/
public int findUnsortedSubarrayViaSort(int[] nums) {
int[] sorted = Arrays.copyOf(nums, nums.length);
Arrays.sort(sorted);
int left = nums.length;
int right = 0;
for (int i = 0; i < sorted.length; i++) {
if (sorted[i] != nums[i]) {
left = Math.min(left, i);
right = Math.max(right, i);
}
}
return right - left < 0 ? 0 : right - left + 1;
}
/**
* Time complexity: O(n^2)
* Space complexity: O(1)
*/
public int findUnsortedSubarrayViaTwoLoops(int[] nums) {
int left = nums.length;
int right = 0;
for (int l = 0; l < nums.length; l++) {
for (int r = l + 1; r < nums.length; r++) {
if (nums[l] > nums[r]) {
left = Math.min(left, l);
right = Math.max(right, r);
}
}
}
return right - left < 0 ? 0 : right - left + 1;
}
}