class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> map = new HashMap<>();
for(String word: words) map.put(word, map.getOrDefault(word, 0) + 1);
PriorityQueue<Map.Entry<String, Integer>> priorityQueue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> stringIntegerEntry, Map.Entry<String, Integer> t1) {
if(stringIntegerEntry.getValue() == t1.getValue()) {
// ascending
return t1.getKey().compareTo(stringIntegerEntry.getKey());
}
else {
// deascending
return stringIntegerEntry.getValue() - t1.getValue();
}
}
});
for(Map.Entry<String, Integer> entry: map.entrySet()) {
String key = entry.getKey();
int count = entry.getValue();
if(priorityQueue.size() == k) {
Map.Entry<String, Integer> top = priorityQueue.peek();
String topKey = top.getKey();
int topCount = top.getValue(); // aaa aa
if(count > topCount ||(count == topCount && key.compareTo(topKey) < 0)) {
priorityQueue.poll();
priorityQueue.offer(entry);
}
}
else priorityQueue.offer(entry);
}
List<Map.Entry<String, Integer>> list = new ArrayList<>();
for(Map.Entry<String, Integer> entry: priorityQueue) list.add(entry);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> stringIntegerEntry, Map.Entry<String, Integer> t1) {
if(stringIntegerEntry.getValue() == t1.getValue()) {
// ascending
return stringIntegerEntry.getKey().compareTo(t1.getKey());
}
else {
// deascending
return t1.getValue() - stringIntegerEntry.getValue();
}
}
});
List<String> list1 = new ArrayList<>();
for(Map.Entry<String, Integer> entry: list) {
list1.add(entry.getKey());
}
return list1;
}
}