#include <stdlib.h>
int *dailyTemperatures(int *temps, int n, int *returnSize) {
int *res = calloc(n, sizeof(int));
int *st = malloc(n * sizeof(int)); // indices with no warmer day yet
int top = 0;
for (int i = 0; i < n; i++) {
while (top > 0 && temps[i] > temps[st[top - 1]]) {
int j = st[--top];
res[j] = i - j;
}
st[top++] = i;
}
free(st);
*returnSize = n;
return res;
}
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> dailyTemperatures(vector<int> &temps) {
stack<int> st;
vector<int> res(temps.size());
for (int i = 0; i < temps.size(); i++) {
while (!st.empty() && temps[i] > temps[st.top()]) {
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return res;
}
};
package main
func dailyTemperatures(temps []int) []int {
res := make([]int, len(temps))
st := []int{} // indices with no warmer day yet
for i, t := range temps {
for len(st) > 0 && t > temps[st[len(st)-1]] {
j := st[len(st)-1]
st = st[:len(st)-1]
res[j] = i - j
}
st = append(st, i)
}
return res
}
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int[] dailyTemperatures(int[] temps) {
int[] res = new int[temps.length];
Deque<Integer> st = new ArrayDeque<>(); // indices with no warmer day yet
for (int i = 0; i < temps.length; i++) {
while (!st.isEmpty() && temps[i] > temps[st.peek()]) {
int j = st.pop();
res[j] = i - j;
}
st.push(i);
}
return res;
}
}
class Solution {
dailyTemperatures(temps) {
const res = new Array(temps.length).fill(0);
const st = []; // indices with no warmer day yet
for (let i = 0; i < temps.length; i++) {
while (st.length && temps[i] > temps[st[st.length - 1]]) {
const j = st.pop();
res[j] = i - j;
}
st.push(i);
}
return res;
}
}
class Solution:
def dailyTemperatures(self, temps: list[int]) -> list[int]:
res = [0] * len(temps)
st = [] # indices with no warmer day yet
for i, t in enumerate(temps):
while st and t > temps[st[-1]]:
j = st.pop()
res[j] = i - j
st.append(i)
return res
struct Solution;
impl Solution {
fn daily_temperatures(temps: Vec<i32>) -> Vec<i32> {
let mut res = vec![0; temps.len()];
let mut st: Vec<usize> = Vec::new(); // indices with no warmer day yet
for (i, &t) in temps.iter().enumerate() {
while let Some(&j) = st.last() {
if t <= temps[j] {
break;
}
st.pop();
res[j] = (i - j) as i32;
}
st.push(i);
}
res
}
}