Untitled
unknown
plain_text
4 years ago
1.1 kB
9
Indexable
class Solution {
class StringFreq {
String word;
int freq;
public StringFreq(String word, int freq) {
this.word = word;
this.freq = freq;
}
}
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);
}
List<StringFreq> list = new ArrayList<>();
for (String key: map.keySet()) {
list.add(new StringFreq(key, map.get(key)));
}
Collections.sort(list, new Comparator<StringFreq>(){
public int compare(StringFreq o1, StringFreq o2) {
if (o1.freq == o2.freq) {
return o2.word.compareTo(o1.word);
}
return o1.freq - o2.freq;
}
});
List<String> results = new ArrayList<>();
for (int i = 0; i < k; i++) {
results.add(list.get(i).word);
}
return results;
}
}Editor is loading...