代码随想录——下一个更大元素 I(Leetcode 496)

题目链接
在这里插入图片描述

我的题解

思想:暴力

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        for(int i = 0; i < nums1.length; i++){
            int j = 0;
            while(j < nums2.length && nums1[i] != nums2[j]){
                j++;
            }
            for(int k = j; k < nums2.length; k++){
                if(nums2[k] > nums1[i]){
                    res[i] = nums2[k];
                    break;
                }
                if(k == nums2.length - 1 && nums2[k] <= nums1[i]){
                    res[i] = -1;
                }
            }
        }
        return res;
    }
}

优秀题解(回顾)

思想:单调栈

class Solution {
    // 定义一个名为Solution的类

    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // 定义一个公共方法nextGreaterElement,接受两个整数数组nums1和nums2作为参数,并返回一个整数数组

        HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
        // 创建一个HashMap,用于存储数组nums1中每个元素的值及其索引

        for(int i = 0; i < nums1.length; i++){
            // 遍历数组nums1
            hash.put(nums1[i], i);
            // 将当前元素及其索引存入HashMap中
        }

        int[] res = new int[nums1.length];
        // 创建一个整数数组res,长度与nums1相同,用于存储结果

        Arrays.fill(res, -1);
        // 使用-1填充数组res,表示默认情况下没有找到更大的元素

        Stack<Integer> stack = new Stack<Integer>();
        // 创建一个栈,用于在遍历nums2时存储元素的索引

        for(int i = 0; i < nums2.length; i++){
            // 遍历数组nums2
            while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]){
                // 当栈不为空,并且栈顶元素对应的nums2中的值小于当前元素时,执行循环
                int pre = nums2[stack.pop()];
                // 弹出栈顶元素,并将其对应的nums2中的值赋给变量pre
                if (hash.containsKey(pre)) {
                    // 如果HashMap中包含pre,说明它是nums1中的元素
                    res[hash.get(pre)] = nums2[i];
                    // 将nums2中当前元素的值设置为nums1中pre元素对应的下一个更大元素
                }
            }
            stack.add(i);
            // 将当前元素的索引压入栈中
        }

        return res;
        // 返回结果数组res
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值