239. 滑动窗口最大值
暴力法能过了一半多一点,但是还是会时间超时。
这道题官方题解给了三种办法,第一种大顶堆go实现起来太麻烦,不像c++一条priority_queue<pair<int, int>> q;就可以实现,所以采用了第二种单调队列的方式来做,只需要保证队列中的元素都是单调的即可,然后再每次插入的时候把不符合的元素筛选出去。
第三章方法分块暂时没看,后续有空再看
func maxSlidingWindow(nums []int, k int) []int {
q := make([]int,0)
ret := make([]int,0)
push := func(i int){
for len(q) > 0 && nums[i] >= nums[q[len(q) - 1]]{
q = q[:len(q) - 1]
}
q = append(q, i)
}
for i := 0; i < k; i++{
push(i)
}
ret = append(ret, nums[q[0]])
for i := k; i < len(nums); i++{
push(i)
for q[0] <= i - k{
q = q[1:]
}
ret = append(ret,nums[q[0]])
}
return ret
}
347.前 K 个高频元素
前 K 个高频元素
go中实现小顶堆的方式,首先需要初始化一个堆的数据结构,然后实现heap.Interface接口的方法
然后调用heap.Init初始化一个切片为堆,并且输入是指针。
func topKFrequent(nums []int, k int) []int {
occurrences := map[int]int{}
for _, num := range nums {
occurrences[num]++
}
h := &IHeap{}
heap.Init(h)
for key, value := range occurrences{
heap.Push(h,[2]int{key, value})
if h.Len() > k{
heap.Pop(h)
}
}
ret := make([]int, k)
for i := 0; i < k; i++{
ret[k - i - 1] = heap.Pop(h).([2]int)[0]
}
return ret
}
type IHeap [][2]int
func (h IHeap) Len() int { return len(h) }
func (h IHeap) Less(i, j int) bool { return h[i][1] < h[j][1] }
func (h IHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IHeap) Push(x interface{}) {
*h = append(*h, x.([2]int))
}
func (h *IHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}