给你两个字符串数组 positive_feedback 和 negative_feedback ,分别包含表示正面的和负面的词汇。不会 有单词同时是正面的和负面的。
一开始,每位学生分数为 0 。每个正面的单词会给学生的分数 加 3 分,每个负面的词会给学生的分数 减 1 分。
给你 n 个学生的评语,用一个下标从 0 开始的字符串数组 report 和一个下标从 0 开始的整数数组 student_id 表示,其中 student_id[i] 表示这名学生的 ID ,这名学生的评语是 report[i] 。每名学生的 ID 互不相同。
给你一个整数 k ,请你返回按照得分 从高到低 最顶尖的 k 名学生。如果有多名学生分数相同,ID 越小排名越前。
PriorityQueue:
Java中的优先队列通常使用PriorityQueue类来实现。PriorityQueue是一个基于堆(heap)的数据结构,用于实现优先队列。以下是PriorityQueue类的一些常用方法:
add(E e) 或 offer(E e):将指定的元素添加到队列中,并根据元素的优先级进行排序。这是插入元素的方法。
remove() 或 poll():删除并返回队列中具有最高优先级的元素。如果队列为空,则返回null。element() 或 peek():查看队列中具有最高优先级的元素,但不将其从队列中移除。如果队列为空,则抛出异常。size():返回队列中的元素数量。isEmpty():检查队列是否为空。clear():清空队列,删除所有元素。toArray():将队列中的元素转换为数组。addAll(Collection<? extends E> c):将指定集合中的所有元素添加到队列中。iterator():返回一个迭代器,允许遍历队列中的元素。
思路:用set存储形容词,将report按照" "进行split,用PriorityQueue存储学生Id与得分。
class Solution {public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {// 定义优先队列PriorityQueue<int[]> q = new PriorityQueue<int[]>((a, b)->{if(a[1]!=b[1]) {return b[1]-a[1];} else {return a[0]-b[0];}});Set<String> posSet = new HashSet(Arrays.asList(positive_feedback));Set<String> negSet = new HashSet(Arrays.asList(negative_feedback));for(int i=0; i<report.length; i++) {String[] str = report[i].split(" ");int scores = 0;for(String s:str) {if(posSet.contains(s)) {scores += 3;} else if(negSet.contains(s)) {scores -= 1;}}q.offer(new int[]{student_id[i], scores});}List<Integer> res = new ArrayList();for(int i=0; i<k; i++) {res.add(q.poll()[0]);}return res;}
}