456. 132 Pattern
Given an array of n
integers nums
, a 132 pattern is a subsequence of three integers nums[i]
, nums[j]
and nums[k]
such that i < j < k
and nums[i] < nums[k] < nums[j]
.
Return true
if there is a 132 pattern in nums
, otherwise return false
.
Example 1:
Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3:
Input: nums = [-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].
Constraints:
n == nums.length
1 <= n <= 3 * 104
-109 <= nums[i] <= 109
题目大意
判断数组中是否存在132模式,及i < j < k,并且nums[i]<nums[k]<nums[j]
思路
贪心思想➕单调递减栈,可以首先从中间的数字nums[j]出发,那么nums[i]肯定要取j前面最小的那个,只有这样才能尽可能地为nums[k]留下位置。因此,可以首先求minj数组,minj[i] = min(nums[0……i])。然后再逆序遍历数组,构造单调递减栈,如果栈不为空并且栈顶元素小于minj[j],就出栈,如果栈不空,并且栈顶元素小于当前的nums[j],那么说明符合要求。
构造的是单调递减栈的原因:若pop完之后,栈不空且栈顶小于nums[i],则直接返回true,若栈不空,且栈顶不小于nums[i],则nums[i]入栈,则说明构造的是单调递减栈。
代码
class Solution {
public boolean find132pattern(int[] nums) {
if(nums.length < 3) return false;
int[] minj = new int[nums.length];
Stack<Integer> s = new Stack<>();
int cur_min = nums[0];
for(int i = 0; i < nums.length; i++){
if(nums[i] < cur_min){
cur_min = nums[i];
}
minj[i] = cur_min;
}
for(int i = nums.length - 1; i >= 0; i--){
if(nums[i] > minj[i]){
while(!s.empty() && s.peek() <= minj[i])
s.pop();
if(!s.empty() && s.peek() < nums[i])
return true;
s.push(nums[i]);
}
}
return false;
}
}