1643185290(1).png

    一个非常典型的,看到题干就能想到 栈 的题目

    1. public int[] dailyTemperatures(int[] temperatures) {
    2. Stack<Map> stack = new Stack<>();
    3. int tLen = temperatures.length;
    4. int[] res = new int[tLen];
    5. //题目规定了length不会小于1,所以不做判断了
    6. Map map = new HashMap();
    7. map.put("index", 0);
    8. map.put("value", temperatures[0]);
    9. stack.push(map);
    10. for(int i=1; i<tLen; i++){
    11. //这一步的作用是当前的元素对比栈顶元素,直到栈顶元素更大
    12. while(!stack.isEmpty()){
    13. Map peekMap = stack.peek();
    14. int temp = (int)peekMap.get("value");
    15. if(temperatures[i] > temp){
    16. res[(int)peekMap.get("index")] = i-temp;
    17. stack.pop();
    18. }else{
    19. break;
    20. }
    21. }
    22. Map tempMap = new HashMap();
    23. tempMap.put("index", i);
    24. tempMap.put("value", temperatures[i]);
    25. stack.push(tempMap);
    26. }
    27. return res;
    28. }