美文网首页Leetcode
Leetcode 496. Next Greater Eleme

Leetcode 496. Next Greater Eleme

作者: SnailTyan | 来源:发表于2021-08-05 08:58 被阅读0次

    文章作者: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 Eleme

        本文链接:https://www.haomeiwen.com/subject/kjoypltx.html