题目
题解
Map + Map
java
class Solution {
public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
// 将分数放到 Map 中
Map<String, Integer> score = new HashMap<>();
for (String s : positive_feedback) {
score.put(s, 3);
}
for (String s : negative_feedback) {
score.put(s, -1);
}
Map<Integer, Integer> idMap = new HashMap<>();
for (int i = 0; i < student_id.length; i++) {
String rep = report[i];
String[] split = rep.split(" ");
int cur = 0;
for (String s : split) {
cur += score.getOrDefault(s, 0);
}
idMap.put(student_id[i], cur);
}
// 对 key 进行排序
return idMap.entrySet().stream().sorted((o1, o2) -> {
if (Objects.equals(o1.getValue(), o2.getValue())) {
return o1.getKey() - o2.getKey();
}
return o2.getValue() - o1.getValue();
}).map(Map.Entry::getKey)
.limit(k)
.collect(Collectors.toList());
}
}
Map + 二维数组
java
class Solution {
public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
// 将分数放在 Map
Map<String, Integer> score = new HashMap<>();
for (String s : positive_feedback) {
score.put(s, 3);
}
for (String s : negative_feedback) {
score.put(s, -1);
}
int[] scores = new int[student_id.length];
int[][] idArrs = new int[student_id.length][2];
for (int i = 0; i < student_id.length; i++) {
String rep = report[i];
String[] split = rep.split(" ");
int cur = 0;
for (String s : split) {
cur += score.getOrDefault(s, 0);
}
// 分数-学号
idArrs[i] = new int[]{cur, student_id[i]};
}
// 二维数组进行排序
Arrays.sort(idArrs, (o1, o2) -> {
if (o1[0] == o2[0]) {
return o1[1] - o2[1];
}
return o2[0] - o1[0];
});
ArrayList<Integer> res = new ArrayList<>(k);
for (int i = 0; i < k; i++) {
res.add(idArrs[i][1]);
}
return res;
}
}
本文由mdnice多平台发布