Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 347. Top K Frequent Elements #347

Open
grandyang opened this issue May 30, 2019 · 1 comment
Open

[LeetCode] 347. Top K Frequent Elements #347

grandyang opened this issue May 30, 2019 · 1 comment

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

 

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.

 

这道题给了我们一个数组,让统计前k个高频的数字,那么对于这类的统计数字的问题,首先应该考虑用 HashMap 来做,建立数字和其出现次数的映射,然后再按照出现次数进行排序。可以用堆排序来做,使用一个最大堆来按照映射次数从大到小排列,在 C++ 中使用 priority_queue 来实现,默认是最大堆,参见代码如下:

 

解法一:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        priority_queue<pair<int, int>> q;
        vector<int> res;
        for (auto a : nums) ++m[a];
        for (auto it : m) q.push({it.second, it.first});
        for (int i = 0; i < k; ++i) {
            res.push_back(q.top().second); q.pop();
        }
        return res;
    }
};

 

当然,既然可以使用最大堆,还有一种可以自动排序的数据结构 TreeMap,也是可以的,这里就不写了,因为跟上面的写法基本没啥区别,就是换了一个数据结构。这里还可以使用桶排序,在建立好数字和其出现次数的映射后,按照其出现次数将数字放到对应的位置中去,这样从桶的后面向前面遍历,最先得到的就是出现次数最多的数字,找到k个后返回即可,参见代码如下:

 

解法二:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        vector<vector<int>> bucket(nums.size() + 1);
        vector<int> res;
        for (auto a : nums) ++m[a];
        for (auto it : m) {
            bucket[it.second].push_back(it.first);
        }
        for (int i = nums.size(); i >= 0; --i) {
            for (int j = 0; j < bucket[i].size(); ++j) {
                res.push_back(bucket[i][j]);
                if (res.size() == k) return res;
            }
        }
        return res;
    }
};

 

Github 同步地址:

#347

 

类似题目:

Kth Largest Element in an Array

Word Frequency

Sort Characters By Frequency

Split Array into Consecutive Subsequences

Top K Frequent Words

K Closest Points to Origin

 

参考资料:

https://leetcode.com/problems/top-k-frequent-elements/

https://leetcode.com/problems/top-k-frequent-elements/discuss/81602/Java-O(n)-Solution-Bucket-Sort

https://leetcode.com/problems/top-k-frequent-elements/discuss/81635/3-Java-Solution-using-Array-MaxHeap-TreeMap

  

LeetCode All in One 题目讲解汇总(持续更新中...)

@lld2006
Copy link

lld2006 commented Jun 28, 2020

Your algorithm's time complexity must be better than O( n log n )
 
解法1应该用min heap, 在大于k的时候就pop出来最小的, 这样time complexity 就减到了nlogk

另外, 从discussion中看到, partition算法的time complexity 平均来说是O(n), 所以在数组较大的时候, 应该用nth_element

class Solution {
public:
vector topKFrequent(vector& nums, int k) {
unordered_map<int, int> cnts;
vector ret;
for(int i = 0; i<nums.size(); ++i){
++cnts[nums[i]];
if(cnts[nums[i]] == 1){
ret.push_back(nums[i]);
}
}
nth_element(ret.begin(), ret.begin()+k-1, ret.end(),
[&cnts](int n1, int n2) {return cnts[n1] > cnts[n2];});
ret.resize(k);
return ret;
}
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants