一、什么是栈
先进后出
二、常用操作
1.原理
访问access:只访问栈顶元素
时间复杂度:O(1)
搜索search:遍历查找某个元素
时间复杂度:O(N)
插入insert:只能在栈顶端插入
时间复杂度:O(1)
删除 delete:只能删除栈顶
时间复杂度:O(1)
2.实现
#创建空list
a=[]
#添加元素
a.append(1)
a.append(2)
a.append(3)
#access
a[-1]
#delete
a.pop()
#get size,O(N)
len(a)
#iterate stack, O(N)
while len(a)>0:
a.pop()
Leetcode练习
496. 下一个更大元素
nums1
中数字 x
的 下一个更大元素 是指 x
在 nums2
中对应位置 右侧 的 第一个 比 x
大的元素。
给你两个 没有重复元素 的数组 nums1
和 nums2
,下标从 0 开始计数,其中nums1
是 nums2
的子集。
对于每个 0 <= i < nums1.length
,找出满足 nums1[i] == nums2[j]
的下标 j
,并且在 nums2
确定 nums2[j]
的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1
。
返回一个长度为 nums1.length
的数组 ans
作为答案,满足 ans[i]
是如上所述的 下一个更大元素 。
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
max_dict={}
stack=[]
for num in reversed(nums2):
while stack and num>=stack[-1]:
stack.pop()
max_dict[num]= stack[-1] if stack else -1
stack.append(num)
return [max_dict[x] for x in nums1]
其他相关Leetcode习题:20,439