"""
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]
"""
"""
用dict实现的木桶排序
解法一:木桶+sort
解法二:木桶+heap(堆)
解法三:维护一个n-k的最大堆((有局限性,如果是第k大,会出问题))。此题是前k大的都append里面了
"""
class Solution1:
def topKFrequent(self, nums, k):
count_list = dict()
res = []
for num in nums:
count_list[num] = count_list.get(num, 0) + 1
#如果count_list[num]没有value,则value是0,否则是value+1
#dict.get(key, default=None)
#key -- 字典中要查找的键。
#default -- 如果指定键的值不存在时,返回该默认值。
t = sorted(count_list.items(), key=lambda l: l[1], reverse=True)
#sorted(iterable, key=None, reverse=False) 返回的是一个list
#iterable -- 可迭代对象
#key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可 #迭代对象中的一个元素来进行排序。
#lambda 输入l是(key,value),输出l[1]是value. 可以理解l[0]是key
#reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
for i in range(k):
res.append(t[i][0]) # t[i][0]表示第i个tuple的第1个元素,t[i][1]则表示第二个元素
return res """
解法二:木桶+heap
python heap
nums = [2, 3, 5, 1, 54, 23, 132]
heap = []
for num in nums:
heapq.heappush(heap, num) # 第一种加入堆
heapq.heapify(nums) #第二种生成堆
print([heapq.heappop(heap) for _ in range(len(nums))]) # 堆排序结果
nums = [1, 3, 4, 5, 2]
print(heapq.nlargest(3, nums)) [5, 4, 3]
print(heapq.nsmallest(3, nums)) [1, 2, 3]
"""
class Solution2:
def topKFrequent(self, nums, k):
import heapq
count_list = dict()
for num in nums:
count_list[num] = count_list.get(num, 0) + 1
p = list() #存储堆排序后的结果
for i in count_list.items():
heapq.heappush(p, (i[1], i[0])) #加入堆,每个结点是个tuple(,)
return [i[1] for i in heapq.nlargest(k, p)] #这里的i[1] 其实是上一行的i[0]
"""
堆默认root是最小值
解法三:维护一个n-k的最大堆(有局限性,最大的值最后入堆,会出问题)
最大堆需要将最小堆的值取反
"""
class Solution3:
def topKFrequent(self, nums, k):
import heapq
count_list = dict()
for num in nums:
count_list[num] = count_list.get(num, 0) + 1
p = list()
res = list()
for i in count_list.items():
heapq.heappush(p, (-i[1], -i[0])) #bug前面没写heapq
if len(p) > len(count_list) - k:
_, val = heapq.heappop(p) #bug前面没写heapq
res.append(-val)
return res

leetcode347 Top K Frequent Elements的更多相关文章

  1. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  2. [leetcode]347. Top K Frequent Elements K个最常见元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  3. Top K Frequent Elements 前K个高频元素

    Top K Frequent Elements 347. Top K Frequent Elements [LeetCode] Top K Frequent Elements 前K个高频元素

  4. 347. Top K Frequent Elements (sort map)

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  5. [LeetCode] Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  6. 347. Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  7. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  8. [Swift]LeetCode347. 前K个高频元素 | Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  9. LeetCode 【347. Top K Frequent Elements】

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

随机推荐

  1. Educational Codeforces Round 80 C. Two Arrays(组合数快速取模)

    You are given two integers nn and mm . Calculate the number of pairs of arrays (a,b)(a,b) such that: ...

  2. Codeforces #590 D 二维树状数组

    题意 给一个10^5之内的字符串(小写字母)时限2s 输入n,有n个操作  (n<10^5) 当操作是1的时候,输入位置x和改变的字母 当操作是2的时候,输入区间l和r,有多少不同的字母 思路 ...

  3. 我的B站主页:https://space.bilibili.com/611212 内有视频题解

    我的B站主页:https://space.bilibili.com/611212 内有视频题解

  4. 《JavaScript高级程序设计》读书笔记(三)基本概念第一小节

    内容---语法 本小节---数据类型 本小节 undefined,null,Boolean---流程控制语句---理解函数 任何语言的核心都必然会描述这门语言最基本的工作原理.而描述的内容通常都要涉及 ...

  5. 二十二 XML校验器

    Struts2提供的校验器及其规则:

  6. spring配置文件1

    applicationContext.xml: <?xml version="1.0" encoding="UTF-8"?><beans xm ...

  7. Spark教程——(11)Spark程序local模式执行、cluster模式执行以及Oozie/Hue执行的设置方式

    本地执行Spark SQL程序: package com.fc //import common.util.{phoenixConnectMode, timeUtil} import org.apach ...

  8. 【PAT甲级】1019 General Palindromic Number (20 分)

    题意: 输入两个正整数n和b(n<=1e9,2<=b<=1e9),分别表示数字的大小和进制大小,求在b进制下n是否是一个回文串,输出“Yes”or“No”,并将数字n在b进制下打印出 ...

  9. 39 (guava包)AbstractScheduledService的使用

    package com.da.tool.guava; import com.google.common.util.concurrent.AbstractScheduledService; import ...

  10. 自定义Toast排队重复显示问题:

    原文 http://blog.csdn.net/baiyuliang2013/article/details/38655495Toast是安卓系统中,用户误操作时或某功能执行完毕时,对用户的一种提示, ...