LeetCode 496. 下一个更大元素 I(Next Greater Element I) 35

496. 下一个更大元素 I
496. Next Greater Element I

题目描述
给定两个没有重复元素的数组 nums1 和 nums2,其中 nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1。

每日一算法2019/6/7Day 35LeetCode496. Next Greater Element I

示例 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于 num1 中的数字 4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于 num1 中的数字 1,第二个数组中数字 1 右边的下一个较大数字是 3。
对于 num1 中的数字 2,第二个数组中没有下一个更大的数字,因此输出 -1。

示例 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于 num1 中的数字 2,第二个数组中的下一个较大数字是 3。
对于 num1 中的数字 4,第二个数组中没有下一个更大的数字,因此输出 -1。

注意:

  1. nums1 和 nums2 中所有元素是唯一的。
  2. nums1 和 nums2 的数组大小都不超过 1000。

Java 实现

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

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()&&num>stack.peek()){
                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;
    }
}

相似题目

扫描二维码关注公众号,回复: 6370333 查看本文章

参考资料

猜你喜欢

转载自www.cnblogs.com/hglibin/p/10987847.html