Leetcode 496[easy]--Next Greater Element I

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:



思路:1.  本题的题意有一点难理解。 有两个array,findNums ,nums, 其中nums1 是nums2 的子集,也就是nums1 中所有的elem 在nums2 中都存在。如果nums1 中的每一个元素在nums2 中相同数值的右边有比该elem大的值,将出现的第一个较大值返回,如果没有这样的值则返回。

            2. 两种方法解题,第一种方法涉及stack和dict。在nums中找到每一个值(dict 的 key)对应的紧靠其后比他大的第一个数(dict的value)。步骤33-36:例:nums =[3,2,1,4,5], 将nums中的值依次放入空list st中,第一轮for 循环得到st=[3]。第二轮 for循环 2< 3,不能进入while 循环,st=[3,2]。第三轮for 循环同理得到 st=[3,2,1]. 第四轮 for循环,因为1<4,进入while 循环, st弹出1,retrun [1:4]进入字典d。因为st的新最后一位 2<4, while循环继续运行,return [2:4],[3:4]进入字典d,而st array 依次pop 出 2,3。此时st 为空,跳出while 循环,进入下一步,st=[4]......33-36结束以后,nums中所有左小右大的元素比对均以key:value的形式进入d。


            

        第二种解法,简单暴力的三重for 循环。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值