题目地址

数据结构:栈、哈希表

思路:遍历nums2,哈希表存储每个元素后第一个大于它的元素。栈为递减栈,当遇到比栈顶元素大的元素,依次弹出元素,存入哈希表。最后遍历nums1,hash[nums[i]]组成的列表即为所求。

如 nums1 = [4,1,2], nums2 = [1,3,4,2].

stack=[1] hash[1]=3 hash[3]=-1(第一次出现该元素,hash值为-1)

stack=[3] hash[3]=4 hash[4]=-1 stack=[4] stack=[4,2] hash[2]=-1

  1. class Solution(object):
  2. def nextGreaterElement(self, nums1, nums2):
  3. """
  4. :type nums1: List[int]
  5. :type nums2: List[int]
  6. :rtype: List[int]
  7. """
  8. stack=[]
  9. hashmap={}
  10. for num in nums2:
  11. while len(stack)>0 and stack[-1]<num :
  12. hashmap[stack.pop()]=num
  13. hashmap[num]=-1
  14. stack.append(num)
  15. return [hashmap[i] for i in nums1]


LeetCode     

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!