# LeetCode 456. 132 Pattern

638人阅读 评论(0)

## 题目要求

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

## 解法分析

1. 该数在某一范围内，返回true
2. 该数超出某一范围，更新这个范围；
3. 该数大于目前所有值，则清空列表，并将当前最小和最大作为范围放入队列；
4. 该数小于当前所有值，则将该值最为范围的起始和结束放入队列。

## 解题代码

    public boolean find132pattern(int[] nums) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
Map<Integer, Integer> ranges = new TreeMap<>();
Set<Integer> keys = new TreeSet<>();
for (int i = 0; i < nums.length; i++) {
if (min > nums[i]) {
min = nums[i];
}
if (max < nums[i]) {
max = nums[i];
}
if (ranges.isEmpty()) {
ranges.put(nums[i], nums[i]);
} else {
for (int key : keys) {
if (key < nums[i]) {
if (nums[i] < ranges.get(key)) {
return true;
} else {
ranges.put(key, nums[i]);
if (max == nums[i]) {
ranges.clear();
keys.clear();
ranges.put(key, nums[i]);
break;
}
}
} else if (key > nums[i]) {
ranges.put(nums[i], nums[i]);
break;
}
}
}
}

return false;
}

## 更好的方法

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：99283次
• 积分：2705
• 等级：
• 排名：第13821名
• 原创：178篇
• 转载：21篇
• 译文：0篇
• 评论：9条
文章分类
阅读排行
评论排行
最新评论