-
Notifications
You must be signed in to change notification settings - Fork 3
/
581.cpp
29 lines (26 loc) · 884 Bytes
/
581.cpp
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
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
stack<int> st;
int n = nums.size();
int leftBoundary = INT_MAX; // correct position
for (int i = 0; i < n; i++) {
while (!st.empty() && nums[i] < nums[st.top()]) {
leftBoundary = min(leftBoundary, st.top());
st.pop();
}
st.push(i);
}
while (!st.empty()) st.pop();
int rightBoundary = INT_MIN; // correct position
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && nums[i] > nums[st.top()]) {
rightBoundary = max(rightBoundary, st.top());
st.pop();
}
st.push(i);
}
if (leftBoundary == INT_MAX) return 0;
return rightBoundary - leftBoundary + 1;
}
};