题目
Given a non-empty array of integers, return the *k* most frequent elements.
示例1:
1 | Input: nums = [1,1,1,2,2,3], k = 2 |
示例2:
1 | Input: nums = [1], k = 1 |
提示:
- 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个即可。
JAVA
1 | class Node { |