func dailyTemperatures(temperatures []int) []int {
// 定义结果集(长度为temperatures的长度)和一个单调栈
res := make([]int, len(temperatures))
stack := []int{0} //单调栈存放元素的下标,先把第一个元素的下标放入
for i := 1; i < len(temperatures); i++ {
top := stack[len(stack)-1] //top存放栈顶元素下标
if temperatures[i] <= temperatures[top] {//注意这里是temperatures[top]
stack = append(stack, i)
} else {
for len(stack) != 0 && temperatures[i] > temperatures[top] {
res[top] = i - top
stack = stack[:len(stack)-1] //弹出栈顶元素
if len(stack) != 0 {
top = stack[len(stack)-1]
}
}
stack = append(stack, i)
}
}
return res
}
func nextGreaterElement(nums1 []int, nums2 []int) []int {
// 初始化结果集(len(nums1),全为-1)和单调栈
res := make([]int, len(nums1))
for i, _ := range res {
res[i] = -1
}
stack := []int{0}
// 初始化map判断并做hash映射
m := make(map[int]int, len(nums1))
for i := 0; i < len(nums1); i++ {
m[nums1[i]] = i //key为元素数值,value为元素下标
}
// 遍历nums2数组,利用单调栈解题
for i := 1; i < len(nums2); i++ {
top := stack[len(stack)-1]
if nums2[i] <= nums2[top] {
stack = append(stack, i)
} else {
for len(stack) != 0 && nums2[i] > nums2[top] {
//判断2中的元素是否在1中出现过
if v, ok := m[nums2[top]]; ok {//注意这里是nums2[top]
res[v] = nums2[i]
}
stack = stack[:len(stack)-1] //弹出栈顶元素
if len(stack) != 0 {
top = stack[len(stack)-1]
}
}
stack = append(stack, i)
}
}
return res
}