"""
给你两个字符串数组 positive_feedback 和 negative_feedback ,分别包含表示正面的和负面的词汇。不会 有单词同时是正面的和负面的。
一开始,每位学生分数为 0 。每个正面的单词会给学生的分数 加 3 分,每个负面的词会给学生的分数 减 1 分。
给你 n 个学生的评语,用一个下标从 0 开始的字符串数组 report 和一个下标从 0 开始的整数数组 student_id 表示,
其中 student_id[i] 表示这名学生的 ID ,这名学生的评语是 report[i] 。每名学生的 ID 互不相同。
给你一个整数 k ,请你返回按照得分 从高到低 最顶尖的 k 名学生。如果有多名学生分数相同,ID 越小排名越前。
"""
from typing import List
class Solution:
def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str],
student_id: List[int], k: int) -> List[int]:
# 用一个字典记录每个学生的分数 {student_id: score}
student_score = {}
"""
这样会超时,要把feedback放到一个字典里
for i in range(len(report)):
# 用一个变量记录当前学生的分数
score = 0
# 遍历每个学生的评语
for word in report[i].split():
# 如果这个词在正面和负面的词汇中
if word in positive_feedback:
# 将这个词的分数加到当前学生的分数上
score += 3
if word in negative_feedback:
score -= 1
"""
feedback = {}
for word in positive_feedback:
feedback[word] = 3
for word in negative_feedback:
feedback[word] = -1
for i in range(len(report)):
# 用一个变量记录当前学生的分数
score = 0
# 遍历每个学生的评语
for word in report[i].split():
# 如果这个词在正面和负面的词汇中
if word in feedback:
# 将这个词的分数加到当前学生的分数上
score += feedback[word]
# 将当前学生的分数记录到字典中
student_score[student_id[i]] = score
# 将字典按照分数从高到低排序
student_score = sorted(student_score.items(), key=lambda x: (-x[1], x[0]))
# 取出前k个学生的id
return [student_score[i][0] for i in range(k)]
LeetCode刷题日记(2512. 奖励最顶尖的 K 名学生)
最新推荐文章于 2024-08-25 02:40:51 发布