LeetCode 496 Next Greater Element I

15 篇文章 1 订阅
10 篇文章 0 订阅

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second

这种需要遍历的同时去掉一些元素,找与其逻辑上相邻但是物理上相邻的元素很适合用stack。

nums1=[4,1,2]

nums2=[1,3,4,2]

比如想找1的next greater。那么从右往左开始,先将栈顶元素以此出栈,直到栈顶大于当前元素或为空。那么当前元素的next greater就是栈顶,然后将当前元素入栈。

next greater简称ng

2: 入栈  ng -1

4: 把2 出栈,栈空,ng -1,4 入栈

3:栈顶大于3,ng 4 ,3入栈

1:栈顶大于1,ng 3,1入栈

最开始我每个元素都这么操作,复杂度n2,至超过了0.5%.后来加上记忆功能,即把nums2中每个元素ng都求出来,然后去搜索。

代码如下:

class Solution(object):
    def nextGreaterElement(self, findNums, nums):
        """
        :type findNums: List[int]
        :type nums: List[int]
        :rtype: List[int]
        """
        stack = [-1]
        dic = {}
        for i in range(len(nums)-1,-1,-1):
            while stack[-1] < nums[i] and stack[-1]!=-1:
                stack.pop()
            stack.append(nums[-1])
            dic[nums[i]] = stack[-2]
        return [dic[i] for i in findNums]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值