代码随想录算法训练营Day13 | 239.滑动窗口最大值、347.前 K 个高频元素

39 阅读1分钟

LeetCode题目

239.滑动窗口最大值

题目链接:Sliding Window Maximum - LeetCode

代码如下:

type MyQueue struct {
	queue []int
}

func NewQueue() MyQueue {
	return MyQueue{
		queue: make([]int, 0),
	}
}

func (this *MyQueue) Front() int {
	return this.queue[0]
}

func (this *MyQueue) Back() int {
	return this.queue[len(this.queue)-1]
}

func (this *MyQueue) Empty() bool {
	return len(this.queue) == 0
}

func (this *MyQueue) Pop(val int) {
	if !this.Empty() && val == this.Front() {
		this.queue = this.queue[1:]
	}
}

func (this *MyQueue) Push(val int) {
	for !this.Empty() && val > this.Back() {
		this.queue = this.queue[:len(this.queue)-1]
	}
	this.queue = append(this.queue, val)
}

func maxSlidingWindow(nums []int, k int) []int {
	queue := NewQueue()
	result := make([]int, 0)
	for i := 0; i < k; i++ {
		queue.Push(nums[i])
	}
	result = append(result, queue.Front())
	for i := k; i < len(nums); i++ {
		queue.Pop(nums[i-k])
		queue.Push(nums[i])
		result = append(result, queue.Front())
	}
	return result
}

347.前 K 个高频元素

题目链接:Top K Frequent Elements - LeetCode

代码如下:

type IntHeap [][2]int

func (h IntHeap) Len() int {
	return len(h)
}

func (h IntHeap) Less(i, j int) bool {
	return h[i][1] < h[j][1]
}

func (h IntHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.([2]int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func topKFrequent(nums []int, k int) []int {
	countMap := make(map[int]int)
	for _, num := range nums {
		countMap[num]++
	}
	h := &IntHeap{}
	for key, val := range countMap {
		heap.Push(h, [2]int{key, val})
		if h.Len() > k {
			heap.Pop(h)
		}
	}
	res := make([]int, h.Len())
	for i := h.Len() - 1; i >= 0; i-- {
		item := heap.Pop(h).([2]int)
		res[i] = item[0]
	}
	return res
}

总结

  1. 单调队列,优先级队列
  2. 堆(heap)是一种满足特定条件的完全二叉树,主要可分为两种类型,大顶堆(max heap):任意节点的值 >= 其子节点的值,以及小顶堆
  3. 堆通常用于实现优先队列,大顶堆相当于元素按从大到小的顺序出队的优先队列。从使用角度来看,我们可以将“优先队列”和“堆”看作等价的数据结构