题解 | JAVA #每日温度# [P0-T2]

每日温度

http://www.nowcoder.com/practice/1f54e163e6944cc7b8759cc09e9c78d8

单调栈直接套娃 记口诀就行:
找右边的就从右往左,找左边的从左往右
找小的就单调递增,找大的就单调递减

这题是找右边的大的,那就从右往左loop, 建单调递减栈

O(n), O(n)

import java.util.*;

public class Solution {
    public int[] temperatures (int[] temperatures) {
      int[] ans = new int[temperatures.length];
      
      // stack规则: 从右向左push index,栈单调递减(相对于temp[index])
      Deque<Integer> stack = new ArrayDeque<>();
      for (int i = temperatures.length-1; i >= 0; i--) {
        while (!stack.isEmpty() && temperatures[stack.peek()] <= temperatures[i])
          stack.pop();
        
        ans[i] = stack.isEmpty() ? 0 : stack.peek() - i;
        stack.push(i);
      }
      
      return ans;
    }
}
全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

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