【代码随想录二刷】Day59-单调栈-Go

代码随想录二刷Day59

今日任务

503.下一个更大元素II
42.接雨水
语言:Go

503. 下一个更大元素II

链接:https://leetcode.cn/problems/next-greater-element-ii/

func nextGreaterElements(nums []int) []int {
    res := make([]int, 2 * len(nums))
    for i := 0; i < len(res); i++ {
        res[i] = -1
    }
    arr := make([]int, 2 * len(nums))
    for i := 0; i < len(nums); i++ {
        arr[i] = nums[i]
        arr[i + len(nums)] = nums[i]
    }
    stack := []int{0}
    for i := 0; i < len(arr); i++ {
        for len(stack) > 0 && arr[i] > arr[stack[len(stack) - 1]] {
            top := stack[len(stack) - 1]
            stack = stack[:len(stack) - 1]
            res[top] = arr[i]
        }
        stack = append(stack, i)
    }
    res = res[:len(nums)]
    return res
}

42. 接雨水

链接:https://leetcode.cn/problems/trapping-rain-water/

func min(i, j int) int {
    if i < j {
        return i
    } else {
        return j
    }
}

func trap(height []int) int {
    res := 0
    stack := []int{0}
    for i := 1; i < len(height); i++ {
        for len(stack) > 0 && height[i] > height[stack[len(stack) - 1]] {
            mid := stack[len(stack) - 1]
            stack = stack[:len(stack) - 1]
            if len(stack) > 0 {
                h := min(height[stack[len(stack) - 1]], height[i]) - height[mid]
                w := i - stack[len(stack) - 1] - 1
                res += h * w
            }
        }
        stack = append(stack, i)
    }
    return res
}

你可能感兴趣的:(代码随想录训练营二刷,leetcode,golang)