【力扣】496. 下一个更大元素 I

496. 下一个更大元素 I

给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。
请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

题解

暴力遍历

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int m = nums1.length, n = nums2.length;
        int[] res = new int[m];
        for(int i = 0; i < m; i++){
            int j = 0;
            while(j < n && nums1[i] != nums2[j]) j++;
            int k = j + 1;
            while(k < n && nums2[j] > nums2[k]){  // 数组中没有重复元素,找到j右边第一个大于nums[j]的元素
                k++;
            }
            res[i] = k < n ? nums2[k] : -1;
        }
        return res;
    }
}

方法二:单调栈 + 哈希表

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        Deque<Integer> stack = new ArrayDeque<>();
        for(int i = nums2.length - 1; i >= 0; i--){
            int num = nums2[i];
            while(!stack.isEmpty() && num > stack.peek()){  // 栈中比当前值小的可以出去,反正也被当前值挡住了
                stack.pop();
            }
            map.put(num, stack.isEmpty() ? -1 : stack.peek());   // 记录下来每个值对应的下一个更大的元素
            stack.push(num);   //该值入栈
        }
        int[] res = new int[nums1.length];
        for (int i = 0; i < nums1.length; ++i) {
            res[i] = map.get(nums1[i]);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值