456. 132 Pattern

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值