2016年12月5日 星期一

[LeetCode] 347. Top K Frequent Elements

轉自LeetCode

Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
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.
<Solution>

想法如下
  • 用 unordered_map 來做 hash table 建表,key 是數值,value是該數值的頻率
  • 用 priority_queue 根據頻率來做 max heap,這樣只要陸續從 queue 前面拿 k 個,就是答案
code 如下
c++
class Solution {
public:
struct myCmp {
bool operator() (pair<int, int> a, pair<int, int> b) {
return a.second < b.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> hashTable;
priority_queue<pair<int, int>, vector<pair<int,int>>, myCmp> maxHeap;
//> create hash table
for(auto n : nums) {
++hashTable[n];
}
//> create max heap
for(auto h : hashTable) {
maxHeap.push(h);
}
//> find top k frequent
vector<int> ans(k,0);
for(int i = 0; i < k; i++) {
ans[i] = maxHeap.top().first;
maxHeap.pop();
}
return ans;
}
};

kotlin 可以更簡化一點
class Solution {
fun topKFrequent(nums: IntArray, k: Int): IntArray {
val map = mutableMapOf<Int,Int>()
for(n in nums) {
map[n] = map[n]?.let{it+1} ?: 1
}
return map.entries
.sortedByDescending {it.value}
.map {it.key}
.take(k)
.toIntArray()
}
}

沒有留言:

張貼留言