一.题目描述
给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
https://leetcode-cn.com/problems/top-k-frequent-elements/
二.代码
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counterMap = new HashMap<>();
for (int num : nums) {
Integer count = counterMap.get(num);
if (count == null) {
counterMap.put(num, 1);
} else {
counterMap.put(num, count + 1);
}
}
List<Integer>[] numList = new List[nums.length + 1];
for (int i = 0; i < numList.length; i++) {
numList[i] = new ArrayList<>();
}
counterMap.forEach((num, count) -> {
numList[count].add(num);
});
int[] res = new int[k];
int idx = 0;
for (int freq = numList.length - 1; freq > 0; freq--) {
for (int num: numList[freq]) {
res[idx++] = num;
if (idx == k) {
return res;
}
}
}
return res;
}
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counterMap = new HashMap<>();
for (int num : nums) {
Integer count = counterMap.get(num);
if (count == null) {
counterMap.put(num, 1);
} else {
counterMap.put(num, count + 1);
}
}
Pair[] pairs = new Pair[counterMap.size()];
int index = 0;
for (Integer key :counterMap.keySet()) {
pairs[index++] = new Pair(key, counterMap.get(key));
}
Pair[] topKPairs = quickSelect(pairs, 0, pairs.length - 1, k - 1);
int[] res = new int[k];
int idx = 0;
for (Pair pair: topKPairs) {
res[idx++] = pair.num;
}
return res;
}
private Pair[] quickSelect(Pair[] pairs, int lo, int hi, int idx) {
if (lo > hi) {
return new Pair[0];
}
int j = partition(pairs, lo, hi);
if (j == idx) {
return Arrays.copyOf(pairs, idx + 1);
}
return j < idx? quickSelect(pairs, j + 1, hi, idx): quickSelect(pairs, lo, j - 1, idx);
}
private int partition(Pair[] pairs, int lo, int hi) {
Pair v = pairs[lo];
int i = lo, j = hi + 1;
while (true) {
while(++i <= hi && pairs[i].freq > v.freq);
while(--j >= lo && pairs[j].freq < v.freq);
if (i >= j) {
break;
}
Pair tmp = pairs[i];
pairs[i] = pairs[j];
pairs[j] = tmp;
}
pairs[lo] = pairs[j];
pairs[j] = v;
return j;
}
}
class Pair {
int num;
int freq;
public Pair(int num, int freq) {
this.num = num;
this.freq = freq;
}
}