每日温度( LeetCode 739 )---栈 (Java)

请添加图片描述

package com.tang.project1.utils;

import java.util.Stack;

public class LeetCode739 {
    static class Solution {
        public static int[] dailyTemperatures(int[] temperatures){
			//用栈存放运算中的数据的下标
			//比如示例1中的73,在栈中存放的是0,74在栈中存放的是1
            Stack<Integer> stack = new Stack<>();
			//用来存放结果的数组
            int[] res = new int[temperatures.length];
			//遍历temperatures数组
            for (int i = 0; i < temperatures.length; i++) {
				//1.栈不为空,栈为空会报错
				//2.栈中的栈顶元素小于即将入栈的元素
                while (!stack.isEmpty()&& temperatures[i] > temperatures[stack.peek()]){
                	//此时把栈顶的元素下标获取
                	//73和74比较的时候,preIndex=0
                	//因为第一遍for循环的时候,没有进入while,直接把0存入栈中
                    int preIndex = stack.peek();
                    //第二遍for循环的时候,进入了while循环,此时i = 1
                    //所以此时为res[0] = 1
                    res[preIndex] = i - preIndex;
                    //将已经比较的元素弹出
                    stack.pop();
                }
                //把当天的温度的下标放入栈中
                stack.push(i);
            }
            //返回已经比较好的元素数组
            return res;
        }
    }

    public static void main(String[] args) {
        int[] temperatures = {73,74,75,71,69,72,76,73};
        Solution.dailyTemperatures(temperatures);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值