496. Next Greater Element I
Posted andywu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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.
题目含义:给两个数组findNums和nums,其中findNums数组是nums数组的子数组。返回一个和findNums等长的数组,其返回的内容为:对于findNums[i],返回的result[i]为nums[i]数组中,findNums[i]的后面的元素中第一个比findNums[i]大的元素。如果不存在这样的元素就写-1。
例如
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. 4:在nums2中4的右边找第一个大于4的数,没有找到,-1
1:在nums2中1的右边找第一个大于1的数,3
2:在nums2中2的右边找第一个大于2的数,没有找到,-1
1 public int[] nextGreaterElement(int[] nums1, int[] nums2) { 2 // 建立每个数字和其右边第一个较大数之间的映射,没有的话就是-1。 3 // 我们遍历原数组中的所有数字,如果此时栈不为空,且栈顶元素小于当前数字, 4 // 说明当前数字就是栈顶元素的右边第一个较大数,那么建立二者的映射,并且去除当前栈顶元素,最后将当前遍历到的数字压入栈。 5 // 当所有数字都建立了映射,那么最后我们可以直接通过哈希表快速的找到子集合中数字的右边较大值 6 int[] result = new int[nums1.length]; 7 Map<Integer, Integer> pairs = new HashMap<>(); 8 Stack<Integer> stack = new Stack<>(); 9 for (int number : nums2) { 10 while (!stack.isEmpty() && stack.peek() < number) { 11 pairs.put(stack.pop(), number); 12 } 13 stack.push(number); 14 } 15 16 for (int i = 0; i < nums1.length; i++) { 17 result[i] = pairs.getOrDefault(nums1[i], -1); 18 } 19 return result; 20 }
以上是关于496. Next Greater Element I的主要内容,如果未能解决你的问题,请参考以下文章
leetcode496 - Next Greater Element I - easy && leetcode503 - Next Greater Element II - medi