Version #1 Sort All with Lambda
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> wordCount = new HashMap<>();
Integer tempCount = null;
List<String> distinctWords = new ArrayList<>();
// O(n) Space + O(n) Time to get Count
for (String word : words) {
tempCount = wordCount.get(word);
if (tempCount == null) {
wordCount.put(word, 1);
distinctWords.add(word);
} else {
wordCount.put(word, tempCount + 1);
}
tempCount = null;
}
Collections.sort(distinctWords, (s1, s2) -> {
if (wordCount.get(s1) == wordCount.get(s2)){
return s1.compareTo(s2);
} else {
return wordCount.get(s2).compareTo(wordCount.get(s1));
}
});
return distinctWords.subList(0, k);
}
}
No comments:
Post a Comment