根据每日 气温
列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0
来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
,你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]
。
提示:气温
列表长度的范围是 [1, 30000]
。每个气温的值的都是 [30, 100]
范围内的整数。
C
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* dailyTemperatures(int* temperatures, int temperaturesSize, int* returnSize)
{
int n=temperaturesSize;
int* res=(int*)malloc(sizeof(int)*n);
memset(res,0,sizeof(int)*n);
int* tmp=(int*)malloc(sizeof(int)*n);
int k=0;
for(int i=0;i<n;i++)
{
while(k!=0 && temperatures[i]>temperatures[tmp[k-1]])
{
res[tmp[k-1]]=i-tmp[k-1];
k--;
}
tmp[k++]=i;
}
*returnSize=n;
return res;
}
C++
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures)
{
int n=temperatures.size();
vector<int> res(n,0);
stack<int> tmp;
for(int i=0;i<n;i++)
{
while(tmp.empty()!=1 && temperatures[i]>temperatures[tmp.top()])
{
res[tmp.top()]=i-tmp.top();
tmp.pop();
}
tmp.push(i);
}
return res;
}
};
python
class Solution:
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
n=len(temperatures)
tmp=[]
res=[0 for i in range(n)]
for i in range(n):
while len(tmp)!=0 and temperatures[i]>temperatures[tmp[-1]]:
res[tmp[-1]]=i-tmp[-1]
del tmp[-1]
tmp.append(i)
return res