原题网址: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].
方法:建一个栈来维持一个单调子序列,倒序扫描。
Java代码
public class Solution {
public boolean find132pattern(int[] nums) {
int s2 = Integer.MIN_VALUE;
Stack<Integer> stack = new Stack<>();
for(int i = nums.length - 1; i >= 0; i--) {
if (nums[i] < s2) return true;
while (!stack.isEmpty() && nums[i] > stack.peek()) {
s2 = stack.pop();
}
stack.push(nums[i]);
}
return false;
}
}
C++代码:
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int s2 = INT_MIN;
stack<int> st;
for(int i = nums.size() - 1; i >= 0; i--) {
if (nums[i] < s2) return true;
while (!st.empty() && nums[i] > st.top()) {
s2 = st.top();
st.pop();
}
st.push(nums[i]);
}
return false;
}
};
Python代码:
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
s2 = -sys.maxint - 1
st = []
for i in range(len(nums) - 1, -1, -1):
if nums[i] < s2: return True
while len(st) > 0 and nums[i] > st[-1]: s2 = st.pop()
st.append(nums[i])
return False
C代码:
bool find132pattern(int* nums, int numsSize) {
int s2 = INT_MIN;
int st[numsSize];
int len = 0;
for(int i = numsSize - 1; i >= 0; i--) {
if (*(nums + i) < s2) return true;
while (len > 0 && *(nums + i) > st[len - 1]) {
s2 = st[--len];
}
st[len++] = *(nums + i);
}
return false;
}
JavaScript代码:
/**
* @param {number[]} nums
* @return {boolean}
*/
var find132pattern = function(nums) {
var s2 = Number.MIN_SAFE_INTEGER;
var st = [];
for(var i = nums.length - 1; i >= 0; i--) {
// console.log("i=" + i.toString() + ", nums[i]=" + nums[i].toString() + ", s2=" + s2.toString());
if (nums[i] < s2) return true;
while (st.length > 0 && nums[i] > st[st.length - 1]) {
s2 = st.pop();
}
st.push(nums[i]);
}
return false;
};
Swift代码:
class Solution {
func find132pattern(_ nums: [Int]) -> Bool {
var s2 = Int.min
var st: [Int] = [Int]()
for i in (0..<nums.count).reversed() {
let num = nums[i]
if num < s2 {
return true
}
while st.count > 0 && num > st.last as Int! {
s2 = st.last as Int!
st.removeLast()
}
st.append(num)
}
return false
}
}
C#代码:
public class Solution {
public bool Find132pattern(int[] nums) {
int s2 = Int32.MinValue;
Stack<int> st = new Stack<int>();
for(int i = nums.Count() - 1; i >= 0; i--) {
if (nums[i] < s2) return true;
while (st.Count > 0 && nums[i] > st.Peek()) {
s2 = st.Pop();
}
st.Push(nums[i]);
}
return false;
}
}