majianyu
2/20/2019 - 9:16 AM

496 下一个更大元素 I

使用栈实现 首先将 nums2的第一个元素入栈 之后遍历 nums2 的剩余元素 如果当前栈不为空, 且当前元素大于栈顶元素, 进行出栈,并将出栈结果和当前元素存储为 map 将当前元素入栈

func nextGreaterElement(findNums []int, nums []int) []int {
    if len(nums) == 0 {
		return []int{}
	}
	result := make([]int, 0)
	m := make(map[int]int)
	st := &Stack{}
	st.Push(nums[0])
	for _, n := range nums[1:] {
		for st.Len() > 0 && n > st.Peek().(int) {
			pop, _ := st.Pop()
			m[pop.(int)] = n
		}
		st.Push(n)
	}
	for _, n := range findNums {
		if v, ok := m[n]; ok {
			result = append(result, v)
		} else {
			result = append(result, -1)
		}
	}
	return result
}
type Stack struct {
	data []interface{}
}
func (this *Stack) Len()int {
	return len(this.data)
}

func (this *Stack) Push(i interface{}) {
	this.data = append([]interface{}{i}, this.data...)
}
func (this *Stack) Peek() interface{} {
	return this.data[0]
}
func (this *Stack) Pop() (interface{}, bool) {
	if len(this.data) == 0 {
		return nil, false
	}
	i := this.Peek()
	this.data = this.data[1:]
	return i, true
}