【python】Leetcode每日一题-132模式
【题目描述】
给定一个整数序列: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].
【分析】
太菜了,不会,看了wp。
-
单调栈
class Solution:
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
stack = []
_MIN = float('-inf') for i in range(len(nums)-1, -1, -1):
if nums[i] < _MIN:
return True
while stack and nums[i] > stack[-1]:
_MIN = stack.pop()
stack.append(nums[i]) return False -
降维
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
length = len(nums)
min = nums[0]
if length<3:
return False
for i in range(length):
min = min if min<nums[i] else nums[i]
if(min == nums[i]):
continue
for j in range(length-1, i, -1):
if(min < nums[j] and nums[j] < nums[i]):
return True
return False -
官方:
枚举两个下标时间复杂度太高了,便尝试枚举一个下标,维护另外两个下标。