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. live555直播

    http://www.cppblog.com/tx7do/archive/2014/05/31/207155.aspx http://blog.csdn.net/sunkwei/article/det ...

  2. return和exit的差别

    #include<stdio.h> #include<sys/types.h> #include<sys/wait.h> #include<unistd.h& ...

  3. .Net——实现IConfigurationSectionHandler接口定义处理程序处理自定义节点

    除了使用.net里面提供的内置处理程序来处理我们的自定义节点外,我们还可以通过多种方法,来自己定义处理类处理我们的自定义节点,本文主要介绍通过实现IConfigurationSectionHandle ...

  4. IE浏览器 get请求缓存问题

    场景: 比较简单是使用的SpringMVC框架,在做资源国际化的时候,遇到了这个问题.具体做的操作是在页面上点击切换语言的时候,需要发起请求在Controller中切换Locale. 问题: 1.开始 ...

  5. 为自己编写的windows应用程序制作安装包

    1 写好了一个windows程序之后如何制作安装包 这个在vs中就可以直接发布了,可以制作msi的安装包和exe的安装包. 2 window应用程序安装包做了哪些事情 rpm安装包的话,只是把相应的文 ...

  6. 那些让你代码思维和能力有较大的提升Java源码(转)

    对于学习J2EE的框架有很大的帮助,代码里使用了各种设计模式.事件机制.Java8语法.代码量也很小,web服务使用Netty作为支持,对HTTP/网络想研究的一定是你的必读品.目前在写 Blade- ...

  7. Nodejs通过Thrift操作hbase卡住原因分析及与javascript的垃圾回收机制的关系

    在最近使用Nodejs通过Thrift操作hbase的时候写了个脚本,不断发送http请求,从而取得hbase下所需的数据,但是在run的过程中for循环并没有执行完全,在执行一部分后会卡住,就再也进 ...

  8. xcode环境变量设置(转载)

    一般我们在xcode里面配置包含工程目录下头文件的时候,都要关联着相对路径和绝对路径,如果只是自己用这个项目,用绝对路径的问题不大,但是如果你把工程发给别人,别人就要在改这个绝对路径,这时候绝对路径的 ...

  9. vue axios拦截器介绍

    关于axios的拦截器是一个作用非常大,非常好用的东西.分为请求拦截器和响应拦截器两种.我一般把拦截器写在main.js里. 1. 请求拦截器 请求拦截器的作用是在请求发送前进行一些操作,例如在每个请 ...

  10. 自动化测试框架selenium+java+TestNG——TestNG详解

    TestNG按顺序执行case package com.testngDemo; import org.testng.annotations.AfterClass; import org.testng. ...