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.
 Approach #1: C++.
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> mp;
for (int i : nums)
mp[i]++;
vector<pair<int, int>> v(mp.begin(), mp.end());
sort(v.begin(), v.end(), cmp);
vector<int> ans;
for (int i = 0; i < k; ++i)
ans.push_back(v[i].first);
return ans;
} private:
static bool cmp(pair<int, int> a, pair<int, int> b) {
return a.second > b.second;
}
};

In order to sort the map with it's value, we can't sort it directly because the iterator type on std::unordered_map is a ForwardIterator, not a RandomAccessIterator, so the first requirement is unsatisfied. The type of the dereferenced iterator is pair<const Key, T>, which is not MoveAssignable (can't assign to const), so the second requirement is also unsatisfied.

we can use a vector to contain the unordered_map, then sort the vector.

Approach #2: Java.

class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length+1];
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>(); for (int n : nums) {
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
} for (int key : frequencyMap.keySet()) {
int frequency = frequencyMap.get(key);
if (bucket[frequency] == null)
bucket[frequency] = new ArrayList<>();
bucket[frequency].add(key);
} List<Integer> res = new ArrayList<>(); for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; --pos) {
if (bucket[pos] != null)
res.addAll(bucket[pos]);
}
return res;
}
}

  

Approach #3: Python.

class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
return zip(*collections.Counter(nums).most_common(k))[0]
 

11.Use Counter to extract the top k frequent elements, most_common(k) return a list of tuples, where the first item of the tuple is the element, and the second item of the tuple is the count, Thus,the built-in zip function could be used to extract the first item from the tuples

Time Submitted Status Runtime Language
3 minutes ago Accepted 40 ms python
5 minutes ago Accepted 12 ms java
20 minutes ago Accepted 12 ms cpp

347. Top K Frequent Elements (sort map)的更多相关文章

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

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

  2. 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 ...

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

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

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

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

  5. 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 ...

  6. 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 ...

  7. [LeetCode] 347. Top K Frequent Elements 解题思路 - Java

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

  8. [LC] 347. 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 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 解题方法 字典 优先级队列 日期 题目地址:https://l ...

随机推荐

  1. Android自动折行TextView Group

    package com.test.testview; import java.util.ArrayList; import android.content.Context; import androi ...

  2. new和delete的基本用法

    前言 new和delete是C++中用来动态管理内存分配的运算符,其用法较为灵活.如果你对它们的几种不同用法感到困惑,混淆,那么接着看下去吧. 功能一:动态管理单变量/对象空间 下面例子使用new为单 ...

  3. 目标检测之积分图---integral image 积分图2

    前面在图像处理一栏中涉及到boxfilter 的时候,简单介绍过积分图,就是每个像素点是左边和上边的累加和,这样的话可以方便均值和方差,以及直方图统计的相关运算,这里再次结合网络资源重新单独对积分图做 ...

  4. C# - Garbage Collection

     The .NET Framework's garbage collector manages the allocation and release of memory for your appl ...

  5. WPF前台数据验证(红框)Validation.ErrorTemplate 附加属性

    WPF 显示验证错误的默认方式是在控件周围绘制红色边框.通常需要对此方法进行自定义,以通过其他方式来显示错误.而且,默认情况下不会显示与验证错误关联的错误消息.常见的要求是仅当存在验证错误时才在工具提 ...

  6. 主题:iframe高度的自适应

    在项目开发中,遇到的一个问题.弹出的页面中有iframe.例 <iframe src="www.baidu.html" width="100%" char ...

  7. [学些东西]用爬虫练习网站来练习burp suite

    最近看爬虫的内容.刚好看到黑板客爬虫第二关http://www.heibanke.com/lesson/crawler_ex01. ADO的i春秋课程里面提到的.另外推荐学习爬虫的好书<web ...

  8. Vue 单页面应用 SEO SPA single page application advantages and disadvantages

    处理 Vue 单页面应用 SEO 的另一种思路 - muwoo - 博客园 https://www.cnblogs.com/tiedaweishao/p/7493971.html SPA网站SEO完美 ...

  9. BAPI_PO_CREATE1 创建PO ch_memory_complete = ‘x',导致hold on 解决方案,

    1.尝试注释标准逻辑,看会不会有什么问题, ZME_BAPI_PO_CUST IF_EX_ME_BAPI_PO_CREATE_02~INBOUND 里面有个控制很费解 我给注释了 2.改用 BAPI_ ...

  10. !推荐:下载abap 源代码

    转自http://blog.sina.com.cn/s/blog_4d1570de0100pvhd.html *@------------------------------------------- ...