Java
class Solution {
public int[] dailyTemperatures(int[] T) {
// 如果長度爲1 直接返回 不必計算
if(T.length <= 1) return new int[]{0};
int[] temp = new int[T.length];
Stack<Integer> stack = new Stack<>();
for (int i = 0 ; i < T.length ; i ++) {
while ( !stack.isEmpty() && T[stack.peek()] < T[i] ) {
temp[stack.peek()] = i - stack.peek() ;
stack.pop() ;
}
stack.push(i);
}
return temp ;
}
}
Go
func dailyTemperatures(T []int) []int {
if len(T) == 1 { return []int{} }
temp := make([]int,len(T))
var stack []int
for i := 0 ; i < len(T) ; i ++ {
for len(stack) != 0 && T[stack[len(stack) - 1]] < T[i] {
temp[stack[len(stack) - 1]] = i - stack[len(stack) - 1]
stack = stack[0 : len(stack) - 1]
}
stack = append(stack, i)
}
return temp
}