Leetcode347. Top K Frequent Elements-优先队列

Leetcode347. Top K Frequent Elements

题目

题目链接

这道题用来练习优先队列(二叉堆结构,Binary Tree)

思路

1.字典计数,按计数排序
2.使用优先队列,优先级就是出现次数

复杂度

字典计数

时间复杂度是 O ( n ) \mathcal{O}(n) O(n),统计个数用时n,
然后对n个数排序(python排序内部用TimSort算法)最差 O ( n l o g n ) \mathcal{O}(nlogn) O(nlogn),最好 O ( n ) \mathcal{O}(n) O(n),平均 O ( n l o g n ) \mathcal{O}(nlogn) O(nlogn),
空间复杂度也是 O ( n ) \mathcal{O}(n) O(n),新建了一个字典,TimSort最差 O ( n ) \mathcal{O}(n) O(n)

优先队列

时间复杂度 O ( n ) \mathcal{O}(n) O(n),统计个数用时n,建立优先队列n,见优先队列构建时间复杂度分析
空间复杂度,要将所有元素都放入队列中, O ( n ) \mathcal{O}(n) O(n)

代码

字典计数

字典计数可以自己写,在python中也有内置类(懒人版)可以用,如
collections.Counter.most_common()

from collections import Counter as ct


class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        return [el[0] for el in ct(nums).most_common(k)]

优先队列

内置优先队列

heapq.nlargest

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count = collections.Counter(nums)   
        return heapq.nlargest(k, count.keys(), key=count.get)
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count = collections.Counter(nums)
        heap = [(value, key) for key, value in count.items()]
        return [key for value, key in heapq.nlargest(k, heap)]

heapq.heapify,heapq.heappop

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        result = []
        my_dict = collections.defaultdict(int)
        for num in nums:
            my_dict[num] += 1
        hp = [(-value, key) for key, value in my_dict.items()]
        heapq.heapify(hp)
        for i in range(k):
            ele = heapq.heappop(hp)
            result.append(ele[1])
        return result

从无到有实现一个优先队列

忘记从哪抄来的了

class Solution:
    def heap(self,i,h):
        if(2*i<=self.n):
            if(self.d[h[i]]<self.d[h[2*i]]):
                a=h[i]
                h[i]=h[2*i]
                h[2*i]=a
                self.heap(2*i,h)
        if(2*i+1<=self.n):
            if(self.d[h[i]]<self.d[h[2*i+1]]):
                a=h[i]
                h[i]=h[2*i+1]
                h[2*i+1]=a
                self.heap(2*i+1,h)
        return        

    def delete(self,h):
        h[1]=h[self.n]
        self.n-=1
        self.heap(1,h)
        return
        
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        self.d={
    
    }
        for i in nums:
            if(i not in self.d):
                self.d[i]=1
            else:
                self.d[i]+=1

        self.n=len(self.d) 
        h=[0]*(self.n+1)
        j=1
        for i in self.d:
            h[j]=i
            j+=1


        i=int(self.n/2)
        while(i>=1):
            self.heap(i,h)
            i-=1

猜你喜欢

转载自blog.csdn.net/qq_17065591/article/details/115429854