//o(nlogn)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<>();
for(int n : nums){
map.put(n,map.getOrDefault(n,0) + 1);
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a));
maxHeap.addAll(map.keySet());
int[] res = new int[k];
for(int i = 0 ; i < k ; i++){
res[i] = maxHeap.poll();
}
return res;
}
}
//o(nlogk)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<>();
for(int n : nums){
map.put(n,map.getOrDefault(n,0) + 1);
}
PriorityQueue<Integer> minHeap = new PriorityQueue<>((a,b) -> map.get(a) - map.get(b));
for(int key : map.keySet()){
minHeap.add(key);
if(minHeap.size() > k) minHeap.poll();
}
int[] res = new int[k];
for(int i = 0 ; i < k ; i ++){
res[i] = minHeap.poll();
}
return res;
}
}
桶排序:时间换空间
class Solution {
public int[] topKFrequent(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length + 1];
Map<Integer,Integer> map = new HashMap<>();
for(int n : nums) map.put(n,map.getOrDefault(n,0)+1);
for(int key : map.keySet()){
int freq = map.get(key);
if(bucket[freq] == null) bucket[freq] = new ArrayList<>();
bucket[freq].add(key);
}
List<Integer> res = new ArrayList<>();
for(int pos = bucket.length - 1 ; pos >= 0 && res.size() < k ; pos --){
if(bucket[pos] != null) res.addAll(bucket[pos]);
}
return res.stream().mapToInt(x -> x).toArray();
}
}
class StreamChecker {
TrieNode root = new TrieNode();
StringBuilder sb = new StringBuilder();
public StreamChecker(String[] words) {
createTrie(words);
}
public boolean query(char letter) {
sb.append(letter);
TrieNode cur = root;
for(int i = sb.length() - 1 ; i >= 0 && cur != null ; i--){
char c = sb.charAt(i);
cur = cur.children[c - 'a'];
if(cur != null && cur.isWord) return true;
}
return false;
}
private void createTrie(String[] words){
for(String s : words){
TrieNode cur = root;
int len = s.length();
for(int i = len - 1 ; i >= 0 ; i--){
char c = s.charAt(i);
if(cur.children[c - 'a'] == null){
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isWord = true;
}
}
}
class TrieNode{
boolean isWord;
TrieNode[] children = new TrieNode[26];
}