forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path132-pattern.cpp
41 lines (39 loc) · 1015 Bytes
/
132-pattern.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
30
31
32
33
34
35
36
37
38
39
40
41
// Time: O(n)
// Space: O(n)
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int ak = numeric_limits<int>::min();
vector<int> stk;
for (int i = size(nums) - 1; i >= 0; --i) {
if (nums[i] < ak) {
return true;
}
while (!empty(stk) && stk.back() < nums[i]) {
ak = stk.back(), stk.pop_back();
}
stk.emplace_back(nums[i]);
}
return false;
}
};
// Time: O(n^2)
// Space: O(1)
class Solution_TLE {
public:
bool find132pattern(vector<int>& nums) {
for (int k = 0; k < size(nums); ++k) {
bool valid = false;
for (int j = 0; j < k; ++j) {
if (nums[j] < nums[k]) {
valid = true;
} else if (nums[j] > nums[k]) {
if (valid) {
return true;
}
}
}
}
return false;
}
};