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. Scrapy爬虫入门系列1 安装

    安装python2.7 参见CentOS升级python 2.6到2.7 安装pip 参见CentOS安装python setuptools and pip‎ 依赖 https://docs.scra ...

  2. 面试题三:设计包括 min 函数的栈。

    3.设计包括 min 函数的栈. 定义栈的数据结构,要求加入一个 min 函数.可以得到栈的最小元素. 要求函数 min.push 以及 pop 的时间复杂度都是 O(1). 思路分析: a.要想一个 ...

  3. 关于java的线程

    1 java的线程也是一个对象 所以,java线程对象也是由gc销毁的. 2 java线程对象等待被销毁的时机 当java线程执行完run()方法之后就在等待被销毁了,所以要一个线程对象不被销毁唯一的 ...

  4. Java类加载器( 死磕 4)

    [正文]Java类加载器(  CLassLoader ) 死磕 之4:  神秘的双亲委托机制 本小节目录 4.1. 每个类加载器都有一个parent父加载器 4.2. 类加载器之间的层次关系 4.3. ...

  5. 面向资源操作的http请求

    Guide | Echo - High performance, minimalist Go web framework https://echo.labstack.com/guide e.POST( ...

  6. Learning Scrapy 中文版翻译 第二章

    为了从网页中提取信息,你有必要对网页的结构做一些了解.我们将快速学习HMTL,HTML数状结构以及用XPath在网页上提取信息 HTML, DOM树结构以及XPath 让我们花一点时间来了解当用户在浏 ...

  7. MySQL常用语句汇总--持续更新(2017-08-10)

    修改表的字段结构: 表:mission_picture,新增字段:content,字段类型:text ALTER TABLE mission_picture ADD content text:

  8. github 版本控制 android studio

    注:本教程实验于android studio 3.1.2 1.下载git :https://gitforwindows.org/   安装 git. 2.配置git 3.配置github 4.上传项目 ...

  9. led子系统【转】

    本文转载自:http://blog.csdn.net/yuanlulu/article/details/6438841 版权声明:本文为博主原创文章,未经博主允许不得转载. ============= ...

  10. c语言之秒数算法

    // 水仙花树:是指一个3位数字,立方和 等于该数本身 // 秒数算法:随便输入一个大于0的数,求出对应的多少小时多少分钟多少秒 #include <stdio.h> / int main ...