【LeetCode】347. 前K个频繁出现的元素

编程入门 行业动态 更新时间:2024-10-09 02:27:44

【LeetCode】347. 前K个<a href=https://www.elefans.com/category/jswz/34/1769556.html style=频繁出现的元素"/>

【LeetCode】347. 前K个频繁出现的元素

问题描述

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

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 = [1,1,1,2,2,3], k = 2
输出: [1,2]例子2:
输入: nums = [1], k = 1
输出: [1]

 

Python 实现

实现一

最直接的解决思路,使用 dict 或者 map 统计元素出现的频率,然后选出出现频率最高的 K 个元素。

class Solution(object):def topKFrequent(self, nums, k):""":type nums: List[int]:type k: int:rtype: List[int]"""if k == len(nums):return nums# Count the frequency with dictionary (key-value pair).dic = {}for num in nums:dic[num] = dic.get(num, 0) + 1# Sort in ascending order; compare frequency first, then compare the elements itself; reverse into descending order.sorted_list_pair = sorted(dic.items(), key=lambda kv:(kv[1], kv[0]), reverse=True)l = [element[0] for element in sorted_list_pair]return l[:k]

实现二:堆

题目要求算法的时间复杂度必须优于O(n log n),出现 lon n 其实就提示了可以通过类似树这样的二分数据结构求解。在这里我们可以用元素的出现的频率作为 key 来构建堆,然后取出最大的 K 的结点即可。(这里直接使用 python 的库实现)

class Solution(object):def topKFrequent(self, nums, k):""":type nums: List[int]:type k: int:rtype: List[int]"""# Method 2: heap.count = collections.Counter(nums)   return heapq.nlargest(k, count.keys(), key=count.get) 

 

链接:/

更多推荐

【LeetCode】347. 前K个频繁出现的元素

本文发布于:2024-02-27 18:26:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1765376.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:频繁   元素   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!