[leetcode] 347. Top K Frequent Elements @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86600911

原题

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:

Input: nums = [1], k = 1
Output: [1]
Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

解法1

使用collections.Counter保存每个数字出现的次数, 然后求前k个频率(倒序), 最后遍历字典, 将符合条件的数字放入结果中.
Time: 3*O(n)
Space: O(1)

代码

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count = collections.Counter(nums)
        res = []
        frequent = sorted(count.values(), reverse = True)[:k]
        for n in count:
            if count[n] in frequent:
                res.append(n)
                
        return res

解法2

利用most_common()方法直接求前k个频率最高的数字, 然后使用list comprehension直接将数字放入列表中.
Time: O(n)
Space: O(1)

代码

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        return [key for key, val in collections.Counter(nums).most_common(k)]

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86600911