Leetcode 496. Next Greater Element I

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Next Greater Element I

2. Solution

**解析:**Version 1,由于元素是唯一的,通过循环找出每个nums2中的满足条件结果保存到字典中,遍历nums1,获得结果。Version 2通过使用栈来寻找满足条件的结果,减少搜索时间。

  • Version 1
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        stat = {}
        for i in range(len(nums2)):
            for j in range(i+1, len(nums2)):
                if nums2[j] > nums2[i]:
                    stat[nums2[i]] = nums2[j]
                    break
            if nums2[i] not in stat:
                stat[nums2[i]] = -1
        result = [stat[x] for x in nums1]
        return result
  • Version 2
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        stat = {num: -1 for num in nums2}
        stack = []
        for num in nums2:
            while stack and stack[-1] < num:
                stat[stack.pop()] = num
            stack.append(num)
        result = [stat[x] for x in nums1]
        return result

Reference

  1. https://leetcode.com/problems/next-greater-element-i/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值