LeetCode No503.下一个更大元素 II

题目描述

在这里插入图片描述

解法一:暴力

在这里插入图片描述
时间复杂度:O(n^2),暴力竟然也能过!!

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        //延长nums数组是原来的2倍
        int[] nums1 = new int[nums.length * 2];
        //复制
        System.arraycopy(nums, 0, nums1, 0, nums.length);
        System.arraycopy(nums, 0, nums1, nums.length, nums.length);
        //暴力求解
        int[] res = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int j = i + 1;
            while (j < nums1.length && nums1[j] <= nums1[i]) {
                ++j;
            }
            if(j == nums1.length){
                //后面没有更大元素
                res[i] = -1;
            }else{
                res[i] = nums1[j];
            }
        }
        return res;
    }
}

解法二:单调栈

在这里插入图片描述

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        //延长nums数组是原来的2倍
        int[] nums1 = new int[nums.length * 2];
        //复制
        System.arraycopy(nums, 0, nums1, 0, nums.length);
        System.arraycopy(nums, 0, nums1, nums.length, nums.length);
        int[] res = new int[nums.length];    //结果数组
        Arrays.fill(res,-1);            //默认是-1
        Stack<int[]> stack = new Stack<>();  //单调栈,int[0]是nums1对应的下标,int[1]是值
        //单调栈
        for (int i = 0; i < nums1.length; i++) {
            int num = nums1[i];  //当前元素
            while (!stack.isEmpty() && stack.peek()[1] < num){
                int[] pop = stack.pop();
                if(pop[0] < nums.length){
                    res[pop[0]] = num;
                }
            }
            stack.push(new int[]{i,num});
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值