刷题顺序以及题解参考卡哥的代码随想录
题目描述
英文版描述
Given an array of integers temperatures represents the daily temperatures, return an arrayanswersuch thatanswer[i]is the number of days you have to wait after thei(th)day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60] Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90] Output: [1,1,0]
Constraints:
- 1 <= temperatures.length <= 10^5
- 30 <= temperatures[i] <= 100
英文版地址
中文版描述
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60] 输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90] 输出: [1,1,0]
提示:
- 1 <= temperatures.length <= 10^5
- 30 <= temperatures[i] <= 100
中文版地址
解题方法
暴力法
果然超时了。。。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
if (temperatures == null) {
return temperatures;
}
int length = temperatures.length;
int[] result = new int[length];
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (temperatures[j] > temperatures[i]) {
result[i] = j - i;
break;
}
}
}
return result;
}
}
复杂度分析
- 时间复杂度:O(n^2),其中 n 是数组的长
- 空间复杂度:O(n)
官方版
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
if (temperatures == null) {
return temperatures;
}
int length = temperatures.length;
int[] result = new int[length];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < length; i++) {
if (!stack.isEmpty()) {
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
Integer pop = stack.pop();
result[pop] = i - pop;
}
}
stack.push(i);
}
return result;
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是数组的元素数
- 空间复杂度:O(n)