Leetcode 496. Next Greater Element I

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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/

以上是关于Leetcode 496. Next Greater Element I的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 496. Next Greater Element I

leetcode-496-Next Greater Element I

[leetcode]Stack-496. Next Greater Element I

496. Next Greater Element I - LeetCode

[leetcode]496. Next Greater Element I下一个较大元素

Leetcode 496. Next Greater Element I