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)