根據(jù)每日 氣溫 列表,請(qǐng)重新生成一個(gè)列表,對(duì)應(yīng)位置的輸入是你需要再等待多久溫度才會(huì)升高的天數(shù)。如果之后都不會(huì)升高,請(qǐng)輸入 0 來代替。
例如,給定一個(gè)列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應(yīng)該是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:氣溫 列表長度的范圍是 [1, 30000]。每個(gè)氣溫的值的都是 [30, 100] 范圍內(nèi)的整數(shù)。
解法1:
思路: 在看棧這個(gè)數(shù)據(jù)結(jié)構(gòu)的時(shí)候碰到這題,沒想出怎么使用棧來解決,最終使用下面這種兩個(gè)下標(biāo)來遍歷的方法。這個(gè)方法缺點(diǎn)在于這一個(gè)數(shù)組我要來回遍歷多次,所以效率低,執(zhí)行時(shí)間長。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] m =new int[temperatures.length];
for(int i=0;i<temperatures.length;i++){
int j = i+1;
while(j<temperatures.length && temperatures[i]>=temperatures[j] ){
j++;
}
if(j ==temperatures.length){
m[i] = 0;
}else{
m[i] = j-i;
}
}
return m;
}
}
解法2:
思路: 該方法使用棧解決,使用棧記錄下標(biāo),這樣只需要走一遍就能完成。
class Solution {
public int[] dailyTemperatures(int[] temperatures)
{
Stack<Integer> stack = new Stack<>();
int size = temperatures.length;
int[] result = new int[size];
Arrays.fill(result,0);
for (int i = 0; i < size; i++)
{
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i])
{
int t = stack.pop();
result[t] = i - t;
}
stack.push(i);
}
return result;
}
}