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]