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++
kotlin 可以更簡化一點
沒有留言:
張貼留言