题目:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
题解:使用Set集合存储正面和负面反馈,加快查找速率。首先先分割字符串,然后查找是否包含对应的正负面反馈,然后算出得分,最后对map集合排序,找出前k名顶尖学生
代码:
改进之前:
- public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
- List<Integer> list = new ArrayList<>();
- HashMap<Integer,Integer> map= new HashMap<>();
- for(int i=0;i<student_id.length;i++)
- {
- int sum=0;
- String res[]=report[i].split(" |\\.");
- for(int j=0;j<res.length;j++)
- {
- for(int p=0;p< Math.max(positive_feedback.length,negative_feedback.length);p++)
- {
- if(p<positive_feedback.length&&res[j].equals(positive_feedback[p]))
- {
- sum=sum+3;
- }
- if(p<negative_feedback.length&&res[j].equals(negative_feedback[p]))
- {
- sum=sum-1;
- }
- }
- }
- map.put(student_id[i],sum);
- }
- List<Map.Entry<Integer, Integer>> sortedList = map.entrySet().stream()
- .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()
- .thenComparing(Map.Entry.comparingByKey()))
- .collect(Collectors.toList());
-
- // 输出排序后的结果
- for (Map.Entry<Integer, Integer> entry : sortedList) {
- // System.out.println(entry.getKey() + ": " + entry.getValue());
- list.add(entry.getKey());
- k--;
- if(k==0)
- break;
- }
- return list;
- }
改进之后:
- public List<Integer> topStudents(String[] positive_feedback, String[] negative_feedback, String[] report, int[] student_id, int k) {
- List<Integer> list = new ArrayList<>();
- Set<String> positiveSet = new HashSet<>(Arrays.asList(positive_feedback));
- Set<String> negativeSet = new HashSet<>(Arrays.asList(negative_feedback));
-
- HashMap<Integer, Integer> map = new HashMap<>();
-
- for (int i = 0; i < student_id.length; i++) {
- int sum = 0;
- String[] res = report[i].split(" |\\.");
- for (String word : res) {
- if (positiveSet.contains(word)) {
- sum += 3;
- }
- if (negativeSet.contains(word)) {
- sum -= 1;
- }
- }
- map.put(student_id[i], sum);
- }
-
- // 以下部分保持不变
- List<Map.Entry<Integer, Integer>> sortedList = map.entrySet().stream()
- .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()
- .thenComparing(Map.Entry.comparingByKey()))
- .collect(Collectors.toList());
-
- for (Map.Entry<Integer, Integer> entry : sortedList) {
- list.add(entry.getKey());
- k--;
- if (k == 0)
- break;
- }
-
- return list;
- }