2512. 奖励最顶尖的 K 名学生
算法掌握:
- 自定义排序
- hash表
- 字符分割
解题思路:
通过题意可知,单词不重复,用hash表存储正面和负面的单词
将每个人的句子分割计算
最后对二维表进行排序即可
java code:
class Solution {
public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
List<Integer> res = new ArrayList<>();
Map<String, Integer> word = new HashMap<>();
for(String p : positive_feedback) word.put(p, 3);
for(String n : negative_feedback) word.put(n, -1);
int[][] score = new int[student_id.length][2];
for(int i = 0; i < student_id.length; i++){
String[] temp = report[i].split(" ");
score[i][0] = student_id[i];
for(String t : temp){
if(word.containsKey(t)){
score[i][1] += word.get(t);
}
}
}
Arrays.sort(score, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[1] == o2[1]){
return o2[0] - o1[0];
}
return o1[1] - o2[1];
}
});
for(int index = score.length - 1; index >= score.length - k; index--){
res.add(score[index][0]);
}
return res;
}
}
c++ code:
class Solution {
public:
static bool compare(const vector<int>& o1, const vector<int>& o2) {
if (o1[1] == o2[1]) {
return o2[0] < o1[0];
}
return o1[1] < o2[1];
}
vector<int> topStudents(vector<string>& positive_feedback, vector<string>& negative_feedback, vector<string>& report, vector<int>& student_id, int k) {
int size = student_id.size();
vector<int> res;
unordered_map<string, int> words;
vector<vector<int>> score(size, vector<int>(2));
for(string& p : positive_feedback) words[p] = 3;
for(string& n : negative_feedback) words[n] = -1;
for(int i = 0; i < size; i++){
score[i][0] = student_id[i];
stringstream ss(report[i]);
string word;
while (getline(ss, word, ' ')) score[i][1] += words[word];
}
sort(score.begin(), score.end(), compare);
for(int i = size - 1; i > size - k - 1; i--) res.push_back(score[i][0]);
return res;
}
};