题解 | #牛牛的喜好排行#
牛牛的喜好排行
https://www.nowcoder.com/practice/1d1ae92247a84d33804ea020c3240df5?tpId=363&tqId=10626426&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param words string字符串一维数组 * @param k int整型 * @return string字符串一维数组 */ public String[] findLeastFrequentSongs(String[] words, int k) { HashMap<String, Integer> hashMap = new HashMap<>(); for (String word : words) { hashMap.put(word, hashMap.getOrDefault(word, 0) + 1); } PriorityQueue<Map.Entry<String, Integer>> priorityQueue = new PriorityQueue<>(( o1, o2) -> { if (o1.getValue().equals(o2.getValue())) { return o1.getKey().compareTo(o2.getKey()); } return o1.getValue() - o2.getValue(); }); Set<Map.Entry<String, Integer>> entries = hashMap.entrySet(); priorityQueue.addAll(entries); String [] result = new String[k]; int index = 0; while (k-- > 0) { result[index++] = Objects.requireNonNull(priorityQueue.poll()).getKey(); } return result; } }
本题知识点分析:
1.哈希表存取
2.优先级队列
3.自定义排序
4.数学模拟
本题解题思路分析:
1.哈希表存取字符串以及出现的次数
2.优先队列用于筛选出频率较少的前k个
3.Lambda表达式自定义排序,如果频率相等,字符串比较,不相等,按升序
4.全部放入优先级队列,小顶堆排序
5.取出前k个,取出同时要判断是否节点为null,Objects.requireNonNullAPI函数
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞支持一下,感谢~