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

题目含义:判断给定的数组中是否存在132模式的子串,例如例3描述的个数

方法一:
复制代码
 1     public boolean find132pattern(int[] nums) {
 2         if (nums.length < 3) return false;
 3         int n = nums.length,i=0,j,k;
 4         while (i<n)
 5         {
 6             while (i<n-2 && nums[i]>=nums[i+1]) i++;
 7             j=i+1;  //此时i比后面的一位小
 8             while (j<n-1 && nums[j]<=nums[j+1]) j++;
 9             k = j+1;//此时j比后面的一位大
10 
11             while (k<n)
12             {
13                 if (nums[k] >nums[i] && nums[k] <nums[j]) return true;  //找到的k比i大而且比j小 满足格式
14                 k++;
15             }
16             i=j+1;
17         }
18         return false;
19     }
复制代码

 

方法二:

复制代码
 1     public boolean find132pattern(int[] nums) {
 2         if (nums.length < 3) return false;
 3         Stack<Integer> seconds = new Stack<>();
 4         Integer third = Integer.MIN_VALUE;
 5         for (int i = nums.length - 1; i >= 0; i--) {
 6             if (nums[i] < third) return true;
 7             else {
 8                 while (!seconds.isEmpty() && nums[i] > seconds.peek()) {
 9                     third = Math.max(third, seconds.pop()); //保证third永远是最大的,保证seconds中的值都大于等于nums[i]
10                 }
11             }
12             seconds.push(nums[i]);
13         }
14         return false;        
15     }
复制代码

 



posted @   daniel456  阅读(206)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示