zoukankan      html  css  js  c++  java
  • [LeetCode]Top K Frequent Elements

    题目描述:

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

    For example,
    Given [1,1,1,2,2,3] and k = 2, return [1,2].

    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.

    题目大意:

    给定一个非空整数数组,返回其前k个出现次数最多的元素。

    测试用例如题目描述。

    注意:

    • 你可以假设k总是有效的,1 ≤ k ≤ 独立元素的个数。

    你的算法时间复杂度必须优于O(n log n),其中n是数组的长度

    第一种解法

    1. 遍历数组nums,利用字典cntDict统计各元素出现次数。
    2. 遍历cntDict,利用嵌套列表freqList记录出现次数为i( i∈[1, n] )的所有元素
    3. 逆序遍历freqList,将其中的前k个元素输出。
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            n = len(nums)
            cntDict = collections.defaultdict(int)
            for i in nums:
                cntDict[i] += 1
            freqList = [[] for i in range(n + 1)]
            for p in cntDict:
                freqList[cntDict[p]] += p,
            ans = []
            for p in range(n, 0, -1):
                ans += freqList[p]
            return ans[:k]

    神一样的存在,下面这个代码

    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            c = collections.Counter(nums)
            return [x[0] for x in c.most_common(k)]
  • 相关阅读:
    ViewPager 滑动页(一)
    Fragment中Button的android:onClick 无法监听相应
    Button的四种Click响应方法
    环形图 自定义(一)
    Progress 自定义(一)-shape
    Button 自定义(一)-shape
    客户机页表遍历
    KVM的ept机制
    linux内核源码中两个重要的宏
    总结
  • 原文地址:https://www.cnblogs.com/UnGeek/p/5491396.html
Copyright © 2011-2022 走看看