class WordNumber {
String word;
Integer number;
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
public class DayCode {
public static void main(String[] args) {
String[] words = new String[]{
"i", "love", "leetcode", "i", "love", "coding"
};
int k = 2;
String[] words1 = new String[]{
"a", "aa", "aaa"
};
int k1 = 1;
List<String> ans = new DayCode().topKFrequent(words, k);
System.out.println(ans.toString());
List<String> ans1 = new DayCode().topKFrequent(words1, k1);
System.out.println(ans1.toString());
}
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<WordNumber> priorityQueue = new PriorityQueue<>(
new Comparator<WordNumber>() {
@Override
public int compare(WordNumber o1, WordNumber o2) {
if (o1.getNumber().equals(o2.getNumber())) {
return o1.getWord().compareTo(o2.getWord());
} else {
return o2.getNumber() - o1.getNumber();
}
}
}
);
for (Map.Entry<String, Integer> i : map.entrySet()) {
WordNumber WordNumber = new WordNumber();
WordNumber.setWord(i.getKey());
WordNumber.setNumber(i.getValue());
priorityQueue.add(WordNumber);
}
List<String> ans = new ArrayList<>();
for (int i = 0; i < k; i++) {
WordNumber temp = priorityQueue.poll();
ans.add(temp.getWord());
}
return ans;
}
}
评论