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.Example:
Input: T=[73,74,75,71,69,72,76,73]
Output: res=[1 ,1 ,4 ,2 ,1 ,1 ,0 ,0]
Approach
Java
import java.util.Arrays;import java.util.Stack;public class DailyTemperatures {public static void main(String[] args) {int[] T = { 73, 74, 75, 71, 69, 72, 76, 73 };int[] res = dailyTemperatures(T);System.out.println(Arrays.toString(res));}static int[] dailyTemperatures(int[] T) {int n = T.length;int res[] = new int[n];Stack<Integer> st = new Stack<Integer>();st.push(0);int index;for (int i = 1; i < n; i++) {while (!st.isEmpty() && T[i] > T[st.peek()]) {index = st.pop();res[index] = i - index;}if (st.isEmpty() || T[i] <= T[st.peek()])st.push(i);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> dailyTemperatures(vector<int> &T){int n = T.size();vector<int> res(n, 0);stack<int> st;st.push(0);int index;for (int i = 1; i < n; i++){while (!st.empty() && T[i] > T[st.top()]){index = st.top();res[index] = i - index;st.pop();}if (st.empty() || T[i] <= T[st.top()])st.push(i);}return res;}int main(){vector<int> T = {73, 74, 75, 71, 69, 72, 76, 73};vector<int> res = dailyTemperatures(T);cout << "[";for (int i = 0; i < res.size() - 1; i++)cout << res[i] << " ,";cout << res[res.size() - 1] << "]";return 0;}
No comments:
Post a Comment