LeetCode739——每日温度

本文详细解析了LeetCode上每日温度问题的三种解法,包括暴力破解、优化后的遍历以及高效的栈方法,深入探讨了每种方法的时间和空间复杂度,并提供了完整的JAVA代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/daily-temperatures/

题目描述:

知识点:栈

思路一:暴力破解法

时间复杂度在最差情况下是O(n ^ 2),其中n为列表长度。空间复杂度是O(1)。

JAVA代码:

public class Solution {

    public int[] dailyTemperatures(int[] T) {
        int n = T.length;
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (T[j] > T[i]) {
                    result[i] = j - i;
                    break;
                }
            }
        }
        return result;
    }

}

LeetCode解题报告:

思路二:对暴力破解法的优化

从后往前遍历列表。最末端的位置一定是0,指针i从n - 2位置从后往前遍历数组T。

当T[i] == T[i + 1]和T[i] < T[i + 1]时均容易分析,但当T[i] > T[i + 1]时,我们需要从索引i + 1 + result[i + 1]开始往后遍历链表寻找那个大于T[i]的值。

时间复杂度在最差情况下是O(n ^ 2),其中n为列表长度。空间复杂度是O(1)。

JAVA代码:

public class Solution {

    public int[] dailyTemperatures(int[] T) {
        int n = T.length;
        int[] result = new int[n];
        result[n - 1] = 0;
        for (int i = n - 2; i >= 0; i--) {
            if (T[i] == T[i + 1]) {
                if (result[i + 1] == 0) {
                    result[i] = 0;
                } else {
                    result[i] = result[i + 1] + 1;
                }
            } else if (T[i] < T[i + 1]) {
                result[i] = 1;
            } else {
                for (int j = i + 1 + result[i + 1]; j < n; j++) {
                    if (T[i] < T[j]) {
                        result[i] = j - i;
                        break;
                    }
                }
            }
        }
        return result;
    }

}

LeetCode解题报告:

思路三:利用栈

栈中存放的是列表中的索引值,假设结果存储在result数组中。

指针i从索引为0的位置开始遍历列表T:

(1)设一个while循环,如果栈不为空且栈顶索引对应的列表T中的值小于当前T[i],我们可以设置result[栈顶值] = 当前索引i - 栈顶值。

(2)在经过上述while循环后,每一个i都需要入栈。

时间复杂度和空间复杂度均是O(n),其中n为列表的长度。

JAVA代码:

public class Solution {

    public int[] dailyTemperatures(int[] T) {
        int n = T.length;
        int[] result = new int[n];
        LinkedList<Integer> stack = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && T[stack.peek()] < T[i]) {
                result[stack.peek()] = i - stack.pop();
            }
            stack.push(i);
        }
        return result;
    }

}

LeetCode解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值