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.
1 2 3 4 5 6 7 8 |
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { var dict = [Int:Int]() nums.forEach { dict[$0] = (dict[$0] == nil ? 0 : dict[$0]! ) + 1 } return dict.sorted(by: { $0.value > $1.value } )[0..<k].map({$0.key}) } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼
❤ 点击这里 -> 订阅《从放弃C语言到使用C++刷算法的简明教程》by 柳婼
❤ 点击这里 -> 订阅PAT甲级乙级、蓝桥杯、GPLT天梯赛、LeetCode题解离线版
