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 循环。