739. Daily Temperatures

题目

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].

解题

暴力破解

遍历i之后的数组,找到第一个比i大的,记录差值即可

func dailyTemperatures(T []int) []int {
    length := len(T)
    result := make([]int, length)

    for i := 0; i < length; i++ {
        for j := i + 1; j < length; j++ {
            if T[j] > T[i] {
                result[i] = j - i
                break
            }
        }
    }
    return result
}
image.png

stack

倒叙遍历,stack记录递减数组。

T = [73, 74, 75, 71, 69, 72, 76, 73]
i = 7, stack = [7 (73)]. ans[i] = 0.
i = 6, stack = [6 (76)]. ans[i] = 0.
i = 5, stack = [5 (72), 6 (76)]. ans[i] = 1.
i = 4, stack = [4 (69), 5 (72), 6 (76)]. ans[i] = 1.
i = 3, stack = [3 (71), 5 (72), 6 (76)]. ans[i] = 2.
i = 2, stack = [2 (75), 6 (76)]. ans[i] = 4.
i = 1, stack = [1 (74), 2 (75), 6 (76)]. ans[i] = 1.
i = 0, stack = [0 (73), 1 (74), 2 (75), 6 (76)]. ans[i] = 1.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容