开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情
前言
小白算法比较菜,希望能激励我每日更新,从leetcode第一题开始,2022年目标2000分,现在1995!!
力扣第 94 场双周赛-力扣
第 94 场双周赛
上2000无望了,反而掉分,又掉20分,大寄啊!!
2512. 奖励最顶尖的 K 名学生
给你两个字符串数组 positive_feedback 和 negative_feedback ,分别包含表示正面的和负面的词汇。不会 有单词同时是正面的和负面的。
一开始,每位学生分数为 0 。每个正面的单词会给学生的分数 加 3 分,每个负面的词会给学生的分数 减 1 分。
给你 n 个学生的评语,用一个下标从 0 开始的字符串数组 report 和一个下标从 0 开始的整数数组 student_id 表示,其中 student_id[i] 表示这名学生的 ID ,这名学生的评语是 report[i] 。每名学生的 ID 互不相同。
给你一个整数 k ,请你返回按照得分 从高到低 最顶尖的 k 名学生。如果有多名学生分数相同,ID 越小排名越前。
示例1:
输入:positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is studious","the student is smart"], student_id = [1,2], k = 2
输出:[1,2]
解释:
两名学生都有 1 个正面词汇,都得到 3 分,学生 1 的 ID 更小所以排名更前。
示例 2:
输入:positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is not studious","the student is smart"], student_id = [1,2], k = 2
输出:[2,1]
解释:
- ID 为 1 的学生有 1 个正面词汇和 1 个负面词汇,所以得分为 3-1=2 分。
- ID 为 2 的学生有 1 个正面词汇,得分为 3 分。
学生 2 分数更高,所以返回 [2,1] 。
提示:
1 <= positive_feedback.length, negative_feedback.length <= 1041 <= positive_feedback[i].length, negative_feedback[j].length <= 100positive_feedback[i]和negative_feedback[j]都只包含小写英文字母。positive_feedback和negative_feedback中不会有相同单词。n == report.length == student_id.length1 <= n <= 104report[i] 只包含小写英文字母和空格 ' '。report[i] 中连续单词之间有单个空格隔开。1 <= report[i].length <= 1001 <= student_id[i] <= 109student_id[i] 的值 互不相同 。1 <= k <= n
代码
基本读题题,用到了set,HashMap和PriorityQueue,set存下积极的评价和消极的评价,map保存每个人的分数,因为同一个id可能会被多次评论。然后遍历map存到queue中,设置好queue的排序规则即可。
class Solution {
public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
HashSet<String> negative = new HashSet<>(Arrays.asList(negative_feedback));
HashSet<String> positive = new HashSet<>(Arrays.asList(positive_feedback));
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < student_id.length; i++) {
String[] s1 = report[i].split(" ");
int temp = 0;
for (String s : s1) {
if (negative.contains(s)) {
temp -= 1;
} else if (positive.contains(s)){
temp += 3;
}
}
map.put(student_id[i], map.getOrDefault(student_id[i], 0) + temp);
}
PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2) -> {
if (o1[0] != o2[0]) {
return o2[0] - o1[0];
} else {
return o1[1] - o2[1];
}
});
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
queue.add(new int[]{entry.getValue(), entry.getKey()});
}
ArrayList<Integer> res = new ArrayList<>();
while (k > 0) {
k--;
int[] poll = queue.poll();
res.add(poll[1]);
}
return res;
}
}
3.结束
第三题被绕进去没绕出来,掉分。