LeetCode#496: Next Greater Element I

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/84178283

Description

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

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.
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.

Solution

这道题的题目理解起来比较费劲,它的意思就是在nums1中的每个数字找到nums2中这个数字右边第一个比它大的数字。例如在上面给的Example中,nums1中的数字2在nums2中右边第一个比它大的数字是3,那么就返回3;而对于nums1中的4,nums2中的4右边已经到了边界,所以没有比它大的数字,因此返回-1。

理清了题目的意思后,我们就开始想想该如何解这道题。以nums1 = [4,1,2], nums2 = [1,3,4,2,5]为例,我们忽略nums1的内容而查看nums2中每个数字的解可以得到1的解为3,3的解为4,4的解为5,2的解为5,而其中4、1、2是在nums1中出现的,因此返回[5,3,5],这里我们不妨使用一个map来保存nums2中每个元素的解,再遍历nums1看看元素在map中是否存在。

以上思路中最核心的一个问题在于该如何得到nums2中每个元素的解。我们可以使用栈来实现,首先将nums2中的第一个元素1加入栈中,而第二个元素3大于栈顶的元素,因此将栈中的1弹出并且将(key = 1, value = 3)放入map中,再将3压入栈;第三个元素4大于栈顶的元素,因此执行上面同样的操作,将3弹出并将(key = 3, value = 4)放入map中,再将4压入栈;第四个元素2小于栈顶元素,因此直接压入栈,此时栈中元素有[4, 2];第五个元素5大于栈顶元素,因此将2弹出,并将(key = 2, value = 5)放入map中,而此时5依然大于栈顶元素4,也将4弹出并将(key = 4, value = 5)放入map中。如此反复,我们就将nums2中有解的键值对都放入了map中,再遍历nums1中取出每个元素的解即可。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for(int num : nums2) {
        	while(!stack.isEmpty() && stack.peek() < num) {
        		map.put(stack.pop(), num);
        	}
        	stack.push(num);
        }
        for(int i = 0; i < nums1.length; i++) {
        	nums1[i] = map.getOrDefault(nums1[i], -1);
        }
        return nums1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/84178283
今日推荐