数据结构之leetcode 347题

1 347题目描述

给出一个列表,输出前k个频率最高的元素。

2 源代码

# 347题
# 我的解答
def topKFrequent(nums, k):
    m = {
     }
    num = []
    for i in nums:
        if i not in m:
            m[i] = 1
        else:
            m[i] += 1
    
    for key, v in m.items():
        p = (v, key)
        num.append(p)
    
    num.sort(key=lambda x: x[0], reverse=True)
    
    print(num)
    ans = []
    for i in range(k):
        ans.append(num[i][1])
#         print(ans, i)
        
    return ans
    
# 347题
# 大佬(柳婼)简洁解答(时间:O(NlogN),空间:O(N))
def topKFrequent(nums, k):
    freq_dict = {
     }
    for v in nums:
        freq_dict[v] = freq_dict.get(v, 0) + 1
    res = list(freq_dict.items())
    res.sort(key=lambda x: x[1], reverse=True)
    return [res[i][0] for i in range(k)]
    
# 347题
# 超级大佬(薛玉洁)简洁解答(用堆,时间:O(N),空间:O(1))

def topKFrequent(nums, k):
    import heapq
    # 先利用字典计数
    fre_dict = {
     }
    for v in nums:
        fre_dict[v] = fre_dict.get(v, 0) + 1
    
    # 创建最小堆
    heap = []
    for key, value in fre_dict.items():
        if len(heap) < k:
            heapq.heappush(heap, (value, key))
            continue
        if value > heap[0][0]:
            heapq.heapreplace(heap, (value, key))
            
    res = []
    while heap:
        res.insert(0, heapq.heappop(heap)[1])
        
    return res
    
topKFrequent([3,0,1,0], 1)  

输出

[0]

你可能感兴趣的:(NLP,leetcode,列表,python,数据结构)