leetcode739 - Daily Temperatures - medium
Given a list of daily temperatures T, return a list such 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 of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
因为我们要找的是相对位置在后的东西,所以从右往左遍历,越近的日子要先比较,所以用一个stack存index(存index就可以了,温度可以通过T[i]来get),两种情况:
1. 当前温度 < stack.top() 那stack.top()就是要找的那一天,记录天数差,不用pop
2. 当前温度 >= stack.top(), 我们尝试pop stack里面的元素,直到找到某天的温度 > 当前温度,如果stack空了也没找到,那就是不存在
不论哪种情况,最后都要把当前i push进stack
这里被pop掉的都没关系的,因为他们都比push进去的小,只要保证保留了右边那些大的数就ok
实现:
1 class Solution { 2 public: 3 vector<int> dailyTemperatures(vector<int>& T) { 4 5 vector<int> res(T.size(), 0); 6 7 stack<int> st; 8 st.push(T.size()-1); 9 10 for (int i=T.size()-2; i>=0; i--){ 11 if (T[i] < T[st.top()]){ 12 res[i] = st.top()-i; 13 } 14 else{ 15 while (!st.empty() && T[st.top()] <= T[i]){ 16 st.pop(); 17 } 18 res[i] = st.empty()? 0 : st.top()-i; 19 } 20 st.push(i); 21 } 22 23 return res; 24 25 } 26 };

浙公网安备 33010602011771号