欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 347. Top K Frequent Elements解题报告(python)

程序员文章站 2022-03-07 19:44:25
...

347. Top K Frequent Elements

  1. Top K Frequent Elements python solution

题目描述

Given a non-empty array of integers, return the k most frequent elements.
LeetCode 347. Top K Frequent Elements解题报告(python)

解析

LeetCode 451. Sort Characters By Frequency属于一个问题

// An highlighted block
from collections import Counter
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        most_common = Counter(nums).most_common()
        sol = []
        for l in range(0,k):
            sol.append(most_common[l][0])
            
        return sol   

Reference

https://leetcode.com/problems/top-k-frequent-elements/discuss/81697/Python-O(n)-solution-without-sort-without-heap-without-quickselect