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] .
Given
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.
想法如下
- 用 unordered_map 來做 hash table 建表,key 是數值,value是該數值的頻率
- 用 priority_queue 根據頻率來做 max heap,這樣只要陸續從 queue 前面拿 k 個,就是答案
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 可以更簡化一點
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
沒有留言:
張貼留言