LeetCode 2512: Reward Top K Students
Problem Description
Explanation:
- Initialize a hashmap to store the points of each student.
- Iterate through the reports and update the points of each student based on the feedback words.
- Sort the students based on points and student IDs in non-increasing order.
- Return the top k students.
Time Complexity: O(n) where n is the number of feedback reports
Space Complexity: O(n) for storing student points
:
Solutions
import java.util.*;
class Solution {
public int[] topKStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
Map<Integer, Integer> points = new HashMap<>();
for (int i = 0; i < report.length; i++) {
String[] words = report[i].split(" ");
int currPoints = 0;
for (String word : words) {
if (Arrays.asList(positive_feedback).contains(word)) {
currPoints += 3;
} else if (Arrays.asList(negative_feedback).contains(word)) {
currPoints -= 1;
}
}
points.put(student_id[i], points.getOrDefault(student_id[i], 0) + currPoints);
}
List<Map.Entry<Integer, Integer>> sortedPoints = new ArrayList<>(points.entrySet());
Collections.sort(sortedPoints, (a, b) -> a.getValue() != b.getValue() ? b.getValue() - a.getValue() : a.getKey() - b.getKey());
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = sortedPoints.get(i).getKey();
}
return result;
}
}
Loading editor...