堆排序
class Solution {
public class Node{
int val;
int cnt;
Node(int val, int cnt) {
this.val = val;
this.cnt = cnt;
}
}
public int[] topKFrequent(int[] nums, int k) {
PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> o1.cnt - o2.cnt);
Arrays.sort(nums);
for(int i = 0, j = 0; j < nums.length; i = j) {
while (j < nums.length && nums[i] == nums[j]) {
j++;
}
Node node = new Node(nums[i], j - i);
System.out.println(node.val + " " + node.cnt);
pq.add(node);
if(pq.size() > k) {
pq.poll();
}
}
int[] ans = new int[k];
int cnt = 0;
while(!pq.isEmpty()) {
ans[cnt++] = pq.poll().val;
}
return ans;
}
}
快排
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// 统计数字出现次数
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; ++i) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
// 记录数字以及出现的次数
List<int[]> values = new ArrayList<int[]>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
values.add(new int[]{entry.getKey(), entry.getValue()});
}
int[] ans = new int[k];
quickSort(values, k - 1, 0, values.size() - 1, ans, 0);
return ans;
}
public void quickSort(List<int[]> values, int k, int start, int end, int[] ans, int index) {
// 将第一个点作为分割点
int[] num = values.get(start);
int i = start;
int j = end;
while(i < j) {
// 移动右指针
while (i < j && values.get(j)[1] < num[1]) {
j--;
}
Collections.swap(values, i, j);
// 移动左指针
while (i < j && values.get(i)[1] >= num[1]) {
i++;
}
Collections.swap(values, i, j);
}
// 如果前k个在分隔点左侧
if(k < i) {
quickSort(values, k, start, i - 1, ans, index);
// 如果第k个刚好在分隔点,或在分割点右侧
} else {
for(int x = start; x <= i; ++x) {
ans[index++] = values.get(x)[0];
}
// 如果前k个在分隔点右侧
if(k > i) {
quickSort(values, k, i + 1, end, ans, index);
}
}
}
}