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 array, so output -1.
Note:
- All elements in
nums1
andnums2
are unique. - The length of both
nums1
andnums2
would not exceed 1000.
下一个更大元素I。
题意是给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
思路是单调栈。创建一个hashmap,记录num2中每个元素和他们各自的下一个更大元素。再遍历num1,看num1里面的元素是否在hashmap中有对应的value,有就输出,没有就返回-1。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int[] nextGreaterElement(int[] nums1, int[] nums2) { 3 HashMap<Integer, Integer> map = new HashMap<>(); 4 Stack<Integer> stack = new Stack<>(); 5 for (int num : nums2) { 6 while (!stack.isEmpty() && stack.peek() < num) { 7 map.put(stack.pop(), num); 8 } 9 stack.push(num); 10 } 11 int[] res = new int[nums1.length]; 12 for (int i = 0; i < res.length; i++) { 13 res[i] = map.getOrDefault(nums1[i], -1); 14 } 15 return res; 16 } 17 }
JavaScript实现
1 /** 2 * @param {number[]} nums1 3 * @param {number[]} nums2 4 * @return {number[]} 5 */ 6 var nextGreaterElement = function (nums1, nums2) { 7 let map = new Map(); 8 let stack = []; 9 for (let num of nums2) { 10 while (stack.length > 0 && stack[stack.length - 1] < num) { 11 map.set(stack.pop(), num); 12 } 13 stack.push(num); 14 } 15 let res = new Array(nums1.length).fill(-1); 16 for (let i = 0; i < res.length; i++) { 17 res[i] = map.get(nums1[i]) || -1; 18 } 19 return res; 20 };