Leetcode 496. Next Greater Element I

2021-07-15 14:07:39 浏览数 (1)

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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 人点赞