topic:
- The next larger element I
Give you two arrays nums1 and nums2 with no repeated elements, where nums1 is a subset of nums2.
Please find out the next greater value of each element in nums1 in nums2.
The next greater element of the number x in nums1 refers to the first element greater than x to the right of the corresponding position in nums2. If it does not exist, the corresponding position outputs -1.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For the number 4 in num1, you can’t enter the second The next higher number is found in the array, so -1 is output.
For the number 1 in num1, the next larger number to the right of the number 1 in the second array is 3.
For the number 2 in num1, there is no next higher number in the second array, so -1 is output.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For the number 2 in num1, the next larger number in the second array It is 3.
For the number 4 in num1, there is no next higher number in the second array, so -1 is output.
prompt:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
All integers in nums1 and nums2 are different from each other
All integers in nums1 also appear in nums2
Advanced: Can you design a solution with a time complexity of O(nums1.length + nums2.length)?
Problem solution ideas:
Maintain a monotonically decreasing stack from left to right, find the area on the right side of the element, the first position larger than itself
Problem solution python code:
class Solution3:
def nextGreaterElement(self, nums1, nums2):
dic, stack = {
}, []
for i in range(len(nums2)):
# 如果是单调就在字典d里面添加,value为key下一个索引位置的值
while stack and stack[-1] < nums2[i]:
dic[stack.pop()] = nums2[i]
stack.append(nums2[i])
return [dic.get(x, -1) for x in nums1]