LeetCode 132 Pattern

原题链接在这里:https://leetcode.com/problems/132-pattern/#/solutions

题目:

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].

题解:

利用Stack<Interval> stk先固定min, 在遇到比stk.peek().min更小的数num就push进新的最小地标new Interval(num, num).

在遇到比stk.peek().min大的数时 先判断是否同时比stk.peek().max小, 若是就return true.

若比stk.peek.max还大就更新stk.peek().max. 此时的min肯定是最小的min, 如果num还比stk下面的max大,那就包含了下面的Interval, pop出来被包含的Interval后, 若是num > stk.peek().min 也return true.

Time Comlexity: O(n). Space: O(n).

AC Java:

 1 public class Solution {
 2     public boolean find132pattern(int[] nums) {
 3         Stack<Interval> stk = new Stack<Interval>();
 4         for(int num : nums){
 5             if(stk.isEmpty() || num<stk.peek().min){
 6                 stk.push(new Interval(num, num));
 7             }else if(num>stk.peek().min){
 8                 Interval top = stk.pop();
 9                 if(num < top.max){
10                     return true;
11                 }else{
12                     top.max = num;
13                     while(!stk.isEmpty() && num>=stk.peek().max){
14                         stk.pop();
15                     }
16                     if(!stk.isEmpty() && num>stk.peek().min){
17                         return true;
18                     }
19                     stk.push(top);
20                 }
21             }
22         }
23         return false;
24     }
25 }
26 
27 class Interval{
28     int min;
29     int max;
30     public Interval(int min, int max){
31         this.min = min;
32         this.max = max;
33     }
34 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6592645.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值