根據(jù)每日 氣溫 列表钓辆,請重新生成一個列表死陆,對應(yīng)位置的輸入是你需要再等待多久溫度才會升高的天數(shù)。如果之后都不會升高其屏,請輸入 0 來代替喇勋。
例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73]偎行,你的輸出應(yīng)該是 [1, 1, 4, 2, 1, 1, 0, 0]川背。
提示:氣溫 列表長度的范圍是 [1, 30000]。每個氣溫的值的都是 [30, 100] 范圍內(nèi)的整數(shù)蛤袒。
解法1:
思路: 在看棧這個數(shù)據(jù)結(jié)構(gòu)的時候碰到這題熄云,沒想出怎么使用棧來解決,最終使用下面這種兩個下標(biāo)來遍歷的方法妙真。這個方法缺點在于這一個數(shù)組我要來回遍歷多次缴允,所以效率低,執(zhí)行時間長珍德。
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;
}
}