496. Next Greater Element I -- 栈

来源:互联网 发布:我的淘宝订单 编辑:程序博客网 时间:2024/06/05 04:31

496. 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: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.

这道题的第一个难点是在读懂题目,其实题目的意思是:nums1中的每个数字在nums2中找到比这个数字大的下一个数字是多少。
nums1 是 nums2的一个子集。
所以采用栈来解决这个问题,先对nums2进行处理,[4,3,2,1,5]例如这个数列,对于前面4个数字,比他们大的下一个数字都是5,所以我们先把不满足条件的数字都压入栈中,然后满足条件后一个个出栈,并把他们和5对应起来写入字典。
最后再利用nums1进行一个个遍历。

findNums = [4,1,2,3]nums = [1,3,4,2]d = {}st = []ans = []for x in nums:    while len(st) and st[-1] < x:        d[st.pop()] = x        print "d: ",d    st.append(x)for x in findNums:    ans.append(d.get(x, -1))    print "x: ", x    print "d.get: ",d.get(x,-1)print ans

这里一共用到了,python中的列表,字典,列表就作为栈来使用,用pop()出栈,append()压栈
d[st.pop()] = x 创建字典
dict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值

0 0
原创粉丝点击