题解 | #单调栈#

单调栈

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

import java.util.*;

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

相关推荐

ALEX_BLX:虽然说聊天记录不可信,不过这个趋势确实如此但我觉得也要想到一点就是卷后端的人里真正有“料”的人又有多少,我说的这个料都不是说一定要到大佬那种级别,而是就一个正常的水平。即使是现在也有很多人是跟风转码的,2-3个月速成后端技术栈的人数不胜数,但今时不同往日没可能靠速成进大厂了。这种情况就跟考研一样,你能上考场就已经打败一半的人了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务