题目

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

``````Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
``````

Example 2:

``````Input: nums = [1], k = 1
Output: [1]``````

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:(优先级队列)

• 【关键数据结构使用】hashMap 用于计数。
• 【关键数据结构使用：优先级队列】PriorityQueue 用于选对top k 的数。（传递给其规则时，用到了函数式编程
``````class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
// build hash map : character and how often it appears
HashMap<Integer, Integer> count = new HashMap();
for (int n: nums) {
count.put(n, count.getOrDefault(n, 0) + 1);
}

// init heap 'the less frequent element first'
PriorityQueue<Integer> heap =
new PriorityQueue<Integer>((n1, n2) -> count.get(n1) - count.get(n2));

// keep k top frequent elements in the heap
for (int n: count.keySet()) {
if (heap.size() > k)
heap.poll();
}

// build output list
while (!heap.isEmpty())
Collections.reverse(top_k);
}
}``````

解答2：（桶排序）

``````public List<Integer> topKFrequent(int[] nums, int k) {

List<Integer>[] bucket = new List[nums.length + 1];
Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();

for (int n : nums) {
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
}

for (int key : frequencyMap.keySet()) {
int frequency = frequencyMap.get(key);
if (bucket[frequency] == null) {
bucket[frequency] = new ArrayList<>();
}
}

List<Integer> res = new ArrayList<>();

for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
if (bucket[pos] != null) {
}
}
return res;
}``````

0条评论