找出数组中每个数的右边第一个比它大的数

问题描述:给出一组数,找出数组中每个数的右边第一个比它大的数

问题分析:利用单调栈,从左至右依次压入数据的索引(若直接压数,则还需要一个数组保存栈中元素所对应的数组位置,如果当前元素小于等于栈顶的索引所对应的数组的值,入栈当前索引,否则将栈顶索引出栈,并在栈顶索引所对应的res数组中记录下当前的值。到最后再检查栈中剩余元素,代表剩余元素右边没有比它大的值,在res对应位置赋值为-1。

代码:


import java.util.Stack;

public class FindFirstBiggerNum {
    public static void main(String[] arg) {
        int array[]=new int[] {1,5,3,6,4,8,9,10};
        int res[]=findMax(array);
        for(int num:res) {
            System.out.println(num);
        }

    }
    public static int[] findMax(int[] array) {
        int len =array.length;
        Stack<Integer> st = new Stack<Integer>();
        int res[]=new int[len];
        int i=0;
        while(i<len) {
            if(st.isEmpty()||array[i]<=array[st.peek()]) {
                st.push(i);
                i++;
            }else {
                res[st.pop()]=array[i];

            }
        }
        while(!st.isEmpty()) {
            res[st.pop()]=-1;
        }
        return res;
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值