456 132 Pattern 132模式
Description:
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.
Follow up:
The O(n^2) is trivial, could you come up with the O(n logn) or the O(n) solution?
Example:
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 <= 10^4
-10^9 <= nums[i] <= 10^9
题目描述:
给定一个整数序列:a1, a2, ..., an,一个132模式的子序列 ai, aj, ak 被定义为:当 i < j < k 时,ai < ak < aj。设计一个算法,当给定有 n 个数字的序列时,验证这个序列中是否含有132模式的子序列。
注意:
n 的值小于15000。
示例 :
示例1:
输入: [1, 2, 3, 4]
输出: False
解释: 序列中不存在132模式的子序列。
示例 2:
输入: [3, 1, 4, 2]
输出: True
解释: 序列中有 1 个132模式的子序列: [1, 4, 2].
示例 3:
输入: [-1, 3, 2, 0]
输出: True
解释: 序列中有 3 个132模式的的子序列: [-1, 3, 2], [-1, 3, 0] 和 [-1, 2, 0].
思路:
用单调栈记录
cur记录模式中的 ‘2’, 单调栈记录模式中的 ‘3’
时间复杂度O(n), 空间复杂度O(n), 数组元素最多出入一次栈
代码:
C++:
class Solution
{
public:
bool find132pattern(vector& nums)
{
stack s;
int cur = INT_MIN, n = nums.size();
for (int i = n - 1; i > -1; i--)
{
if (cur > nums[i]) return true;
while (!s.empty() and nums[i] > s.top())
{
cur = s.top();
s.pop();
}
s.push(nums[i]);
}
return false;
}
};
Java:
class Solution {
public boolean find132pattern(int[] nums) {
int cur = nums[0], n = nums.length;
for (int i = 0; i < n; i++) {
cur = Math.min(cur, nums[i]);
if (cur == nums[i]) continue;
for (int j = n - 1; j > i; j--) if (cur < nums[j] && nums[j] < nums[i]) return true;
}
return false;
}
}
Python:
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
stack, cur = [], float('-inf')
for i in range(len(nums) - 1, -1, -1):
if nums[i] < cur:
return True
while stack and nums[i] > stack[-1]:
cur = stack.pop()
stack.append(nums[i])
return False