Leetcode 456. 132 Pattern

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

132 Pattern

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int size = nums.size();
if(size == 0) {
return false;
}
int min = nums[0];
for(int j = 1; j < size - 1; j++) {
if(nums[j] > min) {
for(int k = j + 1; k < size; k++) {
if(nums[j] > nums[k] && min < nums[k]) {
return true;
}
}
}
else {
min = nums[j];
}
}
return false;
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
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;
}
while(!s.empty() && nums[i] > s.top()) {
third = s.top();
s.pop();
}
s.push(nums[i]);
}
return false;
}
};

Reference

  1. https://leetcode.com/problems/132-pattern/description/
如果有收获,可以请我喝杯咖啡!