Given a list of daily temperatures
, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0
instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
, your output should be [1, 1, 4, 2, 1, 1, 0, 0]
.
Note: The length of temperatures
will be in the range [1, 30000]
. Each temperature will be an integer in the range [30, 100]
.
思路:这题要求给出一个数组,求出数组中每一个数其之后第一个比它大的数字离它有多远,这题可以暴力解决,不过这样时间肯定很长,可以使用一种类似线性DP的方法去解决,
假设该数组为num[0],num[1],…num[n],我们用一个ob[]数组,ob[k]表示比num[k]大的第一个数字在num[]中的位置,假设右为正方向,我们从右向左计算ob[]的值,也就是说,当计算ob[k]的时候,ob[k]-ob[n]都已经得到了正确的值,假设num[k]比num[k+1]要小,毫无疑问ob[k]=k+1;假如num[k]>=num[k+1],那么比较num[k]和num[ob[k+1]]的大小,如果num[k]>= num[ob[k+1]],那么比较num[k]和num[ob[ob[k+1]]]的大小。。。就这样一直比较,假如某一次发现num[ob[ob[…k+1]]…]为-1(-1表示没有比它大的数),那么ob[k]为-1
class Solution {
public:
vector<int>dailyTemperatures(vector<int>& temperatures) {
vector <int> a; vector <int>b;
for (int i = temperatures.size() - 1; i>= 0; i--)
{
if (i + 1<temperatures.size())
{
if(temperatures[i]<temperatures[i + 1]) a.push_back(1);
else
{
int index =temperatures.size() - 1 - i - 1; int count = 1;
int num = a[index]; inttemIndex = i + 1;
while (num != 0)
{
temIndex = temIndex+ num;
if(temperatures[temIndex]>temperatures[i]) { count += num; a.push_back(count);break; }
else { count +=num; index = temperatures.size() - 1 - temIndex; num = a[index]; }
}
if(num == 0)
a.push_back(0);
}
}
else
{
a.push_back(0);
}
}
for (int i = a.size() - 1; i >= 0; i--)
{
b.push_back(a[i]);
}
return b;
}
};