leetcode第347号问题,前K个高频元素

思路:使用优先级队列,在队列中维护k个最高频元素,这样时间复杂度为O(nlogk),满足题目要求,由于go语言没有现成的优先级队列,因此可以根据官方手册用堆实现一个优先级队列,参考http://docscn.studygolang.com/pkg/container/heap/#pkg-index

完整代码

import (
	"container/heap"
	"fmt"
)

type Item struct {
	value    int // The value of the item; arbitrary.
	priority int    // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	//index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	//pq[i].index = i
	//pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	//n := len(*pq)
	item := x.(*Item)
	//item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	//item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func topKFrequent(nums []int, k int) []int {
	res := make([]int,k)
	m := make(map[int]int)
	for _,v := range nums{
		m[v]++
	}
	pq := make(PriorityQueue,0)
	heap.Init(&pq)

	for index,v := range m{
		if pq.Len() == k{
			if v > pq[0].priority {
				heap.Pop(&pq)
				heap.Push(&pq, &Item{index, v})
			}
		}else{
			heap.Push(&pq,&Item{index,v})
		}
	}
	for pq.Len() > 0{
		item := heap.Pop(&pq).(*Item).value
		res[k-1] = item
		k--

	}
	return res
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值