-
Notifications
You must be signed in to change notification settings - Fork 277
/
ShortestUnsortedContinuousSubarray.java
51 lines (43 loc) · 1.1 KB
/
ShortestUnsortedContinuousSubarray.java
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
class Solution {
// TC : O(n)
// SC : O(n)
public int findUnsortedSubarray(int[] nums) {
Stack<Integer> st = new Stack<>();
int left = nums.length-1;
for(int i=0; i< nums.length;){
if(st.empty()){
st.push(i);
i++;
} else{
if(nums[st.peek()] > nums[i]){
left = Math.min(left, st.peek());
st.pop();
} else{
st.push(i);
i++;
}
}
}
st.clear();
int right = 0;
for(int i=nums.length-1;i>=0;){
if(st.empty()){
st.push(i);
i--;
} else{
if(nums[st.peek()] < nums[i]){
right = Math.max(right, st.peek());
st.pop();
} else{
st.push(i);
i--;
}
}
}
if(left >= right){
return 0;
} else{
return right- left +1;
}
}
}