0
点赞
收藏
分享

微信扫一扫

leetcode 栈 496

古得曼_63b6 2022-02-11 阅读 64

栈+哈希表

栈 储存nums2 哈希表储存nums2中每个数字对应的右边第一个大于该数的对应表

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dict, s = {}, []  #dict 哈希表 s 栈 
        for i in nums2: #遍历nums2
            while s and i > s[-1]: #设置循环条件 当s不为空 前找到比栈顶大的元素是进入循环 否则往栈里添加元素
                temp = s.pop() #删除并储存栈顶元素
                dict[temp] = i #将栈顶元素 与 比该元素大的值 设置对应关系存进哈希表
            s.append(i)
        while s : #如果没找到最大值 且遍历完了所有值 意味着没有比栈顶元素大的值了 此时栈中所有值均指向 -1
            temp = s.pop()
            dict[temp] = -1
        return [dict[n] for n in nums1] 

时间复杂度O(n^2) #不知道对不对
空间复杂度O(n) 储存哈希表

举报

相关推荐

0 条评论