題目
給定一個非空的整數數組,返回其中出現頻率前 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;
}
}