题目
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
说明:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
思路:
这个题首先想到的是使用优先队列;具体是先使用map将数据的频数统计,然后再按照频数的大小add到队列中,在这其中需要创建一个Class实现Compare接口来存放到队列中。
代码:
import java.util.*;
public class Solution {
private class myObj implements Comparable<myObj> {
int n, seq;
public myObj() {
}
public myObj(int n, int seq) {
this.n = n;
this.seq = seq;
}
@Override
public int compareTo(myObj o) {
if (this.seq < o.seq) {
return -1;
} else if (this.seq > o.seq) {
return 1;
} else {
return 0;
}
}
}
public List<Integer> topKFrequent(int[] nums, int k) {
/**
* 1.使用map将数据排序
* 2.使用优先队列将数据按照频次排序
* 3.使用LinkedList将数据返回
*/
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int n : nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
PriorityQueue<myObj> queue = new PriorityQueue<>();
for (int key : map.keySet()){
if(queue.size() < k){
queue.add(new myObj(key,map.get(key)));
}else{
queue.add(new myObj(key,map.get(key)));
myObj t = queue.poll();
System.out.println("出来的元素是:"+t.n);
}
}
List<Integer> list = new ArrayList<>(k);
while (!queue.isEmpty()){
list.add(queue.poll().n);
}
return list;
}
}