题解 | #单调栈#

单调栈

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

思路:

  1. 维护栈底到栈顶单调递增
  2. 如果有破坏单调元素curr进来,则维护单调栈的过程中pop出的元素的右所有肯定为curr对应的索引,左索引肯定是pop之后栈顶的元素
  3. 注意,最好单调栈中可能剩余元素,这时说明剩余单调栈中的元素右索引一定为-1,因为右边没有比它小的数,同时要注意单调栈中存储的相等元素情况。
    public int[][] foundMonotoneStack (int[] nums) {
         // write code here
         //思路:栈底到栈顶单调递增,遇到破坏递增的元素,则循环移除,在移除过程中保存移除索引对应的满足条件的左右距离最近的位置
         Stack<Integer> stack=new Stack<>();//栈中存储索引
         int len=nums.length;
         int[][] res=new int[len][2];
         for(int i=0;i<len;i++)
         {
             if(!stack.isEmpty())
             {
                 int right=nums[i];
                 int curr=nums[stack.peek()];
                 while(right<curr)
                 {
                     int currIndex = stack.pop();
                     if(stack.isEmpty())
                     {
                         res[currIndex]=new int[]{-1,i};
                         break;
                     }
                     else
                     {
                         res[currIndex]=new int[]{stack.peek(),i};
                         curr=nums[stack.peek()];
                     }
                 }
             }
             stack.push(i);//大于等于的入栈
         }
         //处理栈中剩余单调元素(有可能都是相等的元素)
         while (!stack.isEmpty())
         {
             Integer currIndex = stack.pop();
             if (!stack.isEmpty() && nums[currIndex]>nums[stack.peek()])
                 res[currIndex]=new int[]{stack.peek(),-1};
             else
                 res[currIndex]=new int[]{-1,-1};
         }
         return res;
     }
全部评论

相关推荐

03-12 13:51
南昌大学 Java
点赞 评论 收藏
分享
群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务