LeetCode-739 Posted on 2020-12-03 Edited on 2025-02-12 In LeetCode 题目 结果 代码遍历1234567891011121314151617181920212223class Solution { public int[] dailyTemperatures(int[] T) { int[] ans = new int[T.length]; for (int i = 0; i < T.length; i++) { // 站在巨人的肩膀上 if (i != 0 && T[i] == T[i - 1] && ans[i - 1] != 0) { ans[i] = ans[i - 1] - 1; continue; } ans[i] = goStraight(T, i); } return ans; } private int goStraight(int[] T, int index) { for (int i = index + 1; i < T.length; i++) { if (T[i] > T[index]) { return i - index; } } return 0; }} 单调栈12345678910111213141516class Solution { public int[] dailyTemperatures(int[] T) { int[] ans = new int[T.length]; Deque<Integer> stack = new LinkedList<>(); for (int i = 0; i < T.length; i++) { // 使栈中的元素从栈底到栈顶递减 while (!stack.isEmpty() && T[i] > T[stack.peek()]) { int index = stack.pop(); ans[index] = i - index; } stack.push(i); } // 此时栈中还剩最后一个元素,但最后一个元素对应的ans必然是0,不必考虑 return ans; }} 复杂度遍历: 时间复杂度:O(n²) 空间复杂度:O(n) 单调栈: 时间复杂度:O(n),所有元素遍历一遍,进栈一次,出栈一次。 空间复杂度:O(n) Donate WeChat Pay Alipay