华为题:每日温度
如果之后都不会升高,则 answer[i] = 0。
输入描述
第一行输入一个整数 n。
第二行输入 n 个整数,表示每天的温度。
输出描述
输出 n 个整数,表示每天需要等待的天数。
示例 1
输入
text
8
73 74 75 71 69 72 76 73
输出
text
1 1 4 2 1 1 0 0
C++ 解法
cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> t(n);
for (int i = 0; i < n; i++) cin >> t[i];
vector<int> ans(n, 0);
stack<int> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && t[i] > t[st.top()]) {
int idx = st.top();
st.pop();
ans[idx] = i - idx;
}
st.push(i);
}
for (int i = 0; i < n; i++) {
if (i) cout << " ";
cout << ans[i];
}
cout << endl;
return 0;
}