题解 | #单调栈#

单调栈

http://www.nowcoder.com/practice/ae25fb47d34144a08a0f8ff67e8e7fb5



public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int一维数组 
     * @return int二维数组
     */
    public int[][] foundMonotoneStack (int[] nums) {
        // write code here
        int[][] result = new int[nums.length][2];
        if(nums == null || nums.length == 0){
            return result;
        }
        Stack<Integer> stack = new Stack<>();
        
        for(int i = 0;i< nums.length; i++){
            while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){
                stack.pop();
            }
            if(stack.isEmpty()){
                result[i][0] = -1;
            }else{
                result[i][0] = stack.peek();
            }
            stack.push(i);
        }
        stack.clear();
        
        for(int j = nums.length - 1;j >= 0;j--){
            while(!stack.isEmpty() && nums[stack.peek()] >= nums[j]){
                stack.pop();
            }
            if(stack.isEmpty()){
                result[j][1]= -1;
            }else{
                result[j][1] = stack.peek();
            }
            stack.push(j);
        }
        return result;
    }
}
全部评论

相关推荐

2025-12-14 11:43
黑龙江大学 Java
用微笑面对困难:确实比较烂,可以这么修改:加上大学的qs排名,然后大学简介要写一些,然后硕士大学加大加粗,科研经历第一句话都写上在复旦大学时,主要负责xxxx,简历左上角把学校logo写上,建议用复旦大学的简历模板
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务