-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path132Pattern.h
More file actions
89 lines (58 loc) · 1.87 KB
/
132Pattern.h
File metadata and controls
89 lines (58 loc) · 1.87 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
84
85
86
87
88
89
/*
bluepp
2017-01-09
May the force be with me!
https://leetcode.com/problems/132-pattern/
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj,
ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and
checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
Example 1:
Input: [1, 2, 3, 4]
Output: False
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: [3, 1, 4, 2]
Output: True
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3:
Input: [-1, 3, 2, 0]
Output: True
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
Show Tags
*/
bool find132pattern(vector<int>& nums) {
if (nums.size() <= 2) return false;
int n = nums.size(), i = 0, j = 0, k = 0;
while (i < n) {
while (i < n - 1 && nums[i] >= nums[i + 1]) ++i;
j = i + 1;
while (j < n - 1 && nums[j] <= nums[j + 1]) ++j;
k = j + 1;
while (k < n) {
if (nums[k] > nums[i] && nums[k] < nums[j]) return true;
++k;
}
i = j + 1;
}
return false;
}
/* stack */
bool find132pattern(vector<int>& nums) {
int third = INT_MIN;
stack<int> s;
for (int i = nums.size()-1; i >= 0; i--)
{
if (nums[i] < third) return true;
else
{
while (!s.empty() && nums[i] > s.top())
{
third = s.top();
s.pop();
}
}
s.push(nums[i]);
}
return false;
}