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. 自动提交form表单

    <form class="form-inline" name='MD5form' method="post" action="<?php ...

  2. 服务器启动时Webapp的web.xml中配置的加载顺序(转载)

    一 1.启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener>和<context-param>两个结点. 2.紧急着,容创建一个Ser ...

  3. MySQL 存储过程 (2)

    通过存储过程查询数据库返回条数操作 第一步:登录自定义用户建立存储过程需要调用测试用到的student表,具体操作如下 (1) 登录用户

  4. mac下使用gnu gcc

    1 mac下安装gnu gcc brew search gcc brew install gcc@6 2 mac下编写c/c++代码所需的标准库和头文件 2.1 标准c++的库的头文件都是标准化了的, ...

  5. Interpreter Pattern

    1.Interpreter模式的目的就是提供一个一门定义语言的语法表示的解释器,然后通过这个解释器来解释语言中的句子. 2.Interpreter模式结构图 3.实现 #ifndef _CONTEXT ...

  6. AndroidPageObjectTest_TimeOutManagement.java

    以下代码使用ApiDemos-debug.apk进行测试 //这个脚本用于演示PageFactory的功能:设置timeout时间. package com.saucelabs.appium; imp ...

  7. Docker的远程访问

    $docker : info (10.211.55是另一台服务器的地址) 频繁访问远程的docker服务器使用-H选项很麻烦,使用环境变量DOCKER_HOST, $export DOCKER_HOS ...

  8. BZOJ 1624 [Usaco2008 Open] Clear And Present Danger 寻宝之路:floyd

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1624 题意: 农夫约翰正驾驶一条小艇在牛勒比海上航行. 海上有N(1≤N≤100)个岛屿, ...

  9. NLP任务中的基本指标(precision and recall )

    >>以下内容参考wikipedia. https://en.wikipedia.org/wiki/Precision_and_recall 精确度 precision  = (true p ...

  10. 在IAR(EWARM)中移植STM32固件库

    一.移植环境说明 (1).win10系统 (2).IAR(EWARM)7.7 (3).STM32标准固件库3.5.0 http://www.st.com/content/st_com/en/produ ...