【两次过】【Comparator】Lintcode 613. 优秀成绩

本文介绍了一种算法,用于处理学生考试成绩数据,通过两种方法找出每位学生最高五个分数的平均值,一是通过排序,二是利用优先队列实现更高效的数据处理。

每个学生有两个属性 id 和 scores。找到每个学生最高的5个分数的平均值。

样例

例1:

输入: 
[[1,91],[1,92],[2,93],[2,99],[2,98],[2,97],[1,60],[1,58],[2,100],[1,61]]
输出:
1: 72.40
2: 97.40

例2:

输入:
[[1,90],[1,90],[1,90],[1,90],[1,90],[1,90]]
输出: 
1: 90.00

解题思路1:

排序。按照id升序再按照score降序,最后再依次取每个id的前5项。

/**
 * Definition for a Record
 * class Record {
 *     public int id, score;
 *     public Record(int id, int score){
 *         this.id = id;
 *         this.score = score;
 *     }
 * }
 */
public class Solution {
    /**
     * @param results a list of <student_id, score>
     * @return find the average of 5 highest scores for each person
     * Map<Integer, Double> (student_id, average_score)
     */
    public Map<Integer, Double> highFive(Record[] results) {
        // Write your code here
        Map<Integer, Double> map = new HashMap<>();
        if(results == null || results.length < 5)
            return map;
        
        Arrays.sort(results, new Comparator<Record>(){
            @Override
            public int compare(Record a, Record b){
                if(a.id != b.id)
                    return a.id - b.id;
                else
                    return b.score - a.score;
            }
        });
        
        int reId = results[0].id;
        for(int i=0; i<results.length;){
            int times = 0;
            int sum = 0;
            
            while(i < results.length && results[i].id == reId && times < 5){
                sum += results[i].score;
                times++;
                i++;
            }
            
            if(sum != 0){
                map.put(reId, (double)sum/5);
                reId++;
            }else
                i++;
        }
        
        return map;
    }
}

解题思路2:

采用优先队列。使用Map<Integer, PriorityQueue<Integer>>来存储id以及id对应的score集合,始终保持优先队列只存储前5大的元素即可。

/**
 * Definition for a Record
 * class Record {
 *     public int id, score;
 *     public Record(int id, int score){
 *         this.id = id;
 *         this.score = score;
 *     }
 * }
 */
public class Solution {
    /**
     * @param results a list of <student_id, score>
     * @return find the average of 5 highest scores for each person
     * Map<Integer, Double> (student_id, average_score)
     */
    public Map<Integer, Double> highFive(Record[] results) {
        // Write your code here
        Map<Integer, Double> res = new HashMap<>();
        if(results == null || results.length < 5)
            return res;
        
        Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
        for(int i=0; i<results.length; i++){
            if(!map.containsKey(results[i].id))
                map.put(results[i].id, new PriorityQueue<Integer>());
            
            PriorityQueue<Integer> queue = map.get(results[i].id);
            if(queue.size() < 5)
                queue.add(results[i].score);
            else{
                if(results[i].score > queue.peek()){
                    queue.poll();
                    queue.add(results[i].score);
                }
            }
        }
        
        for(Integer id : map.keySet()){
            PriorityQueue<Integer> queue = map.get(id);
            double sum = 0;
            while(!queue.isEmpty())
                sum += queue.poll();
            
            res.put(id, sum/5.0);
        }
        
        return res;
    }
}

 

<think>我们正在处理一个Map.Entry类型的优先队列,需要使用匿名Comparator来定义排序规则。根据引用[2],Map.Entry本身没有实现Comparable,因此我们需要在创建优先队列时提供一个Comparator。我们可以采用匿名内部类的方式实现Comparator,并覆盖compare方法。假设我们要根据Map.Entry的键(Key)进行排序,或者根据值(Value)进行排序。引用[4]中提供了两种写法,这里我们使用匿名Comparator(写法二)。例如,我们创建一个优先队列,按照Map.Entry的键(Integer类型)升序排列:PriorityQueue<Map.Entry<Integer,Integer>>queue=newPriorityQueue<>(newComparator<Map.Entry<Integer,Integer>>(){@Overridepublicintcompare(Map.Entry<Integer,Integer>o1,Map.Entry<Integer,Integer>o2){//升序:o1的键减去o2的键returno1.getKey()-o2.getKey();}});或者按照值降序排列:PriorityQueue<Map.Entry<Integer,Integer>>queue=newPriorityQueue<>(newComparator<Map.Entry<Integer,Integer>>(){@Overridepublicintcompare(Map.Entry<Integer,Integer>o1,Map.Entry<Integer,Integer>o2){//降序:o2的值减去o1的值returno2.getValue()-o1.getValue();}});注意:使用减法来实现比较在某些情况下可能溢出,更安全的做法是使用Integer.compare(a,b)方法。因此,改进后的升序排列(按值):returnInteger.compare(o1.getValue(),o2.getValue());降序排列(按值):returnInteger.compare(o2.getValue(),o1.getValue());下面我们将给出完整示例,包括创建Map,添加条目到优先队列,然后按顺序取出。注意:我们不会直接向优先队列中添加Map.Entry,而是通过Map.entrySet()获取条目集合,然后逐个添加(如引用[1]所示)。由于用户的需求是处理Map.Entry类型,我们假设键值都是Integer类型(实际中可以是其他类型,比较逻辑需相应调整)。完整代码示例:</think> 在 Java 中为 `Map.Entry` 类型创建优先队列时,可以使用匿名 `Comparator` 定义自定义排序规则。以下是具体实现方法及完整代码示例: ### 完整实现代码 ```java import java.util.*; public class MapEntryPriorityQueueExample { public static void main(String[] args) { // 1. 创建原始Map并填充数据 Map<String, Integer> map = new HashMap<>(); map.put("A", 30); map.put("B", 10); map.put("C", 50); map.put("D", 20); // 2. 创建优先队列,使用匿名Comparator按值升序排序 PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) { // 比较条目值:e1.getValue() - e2.getValue() return Integer.compare(e1.getValue(), e2.getValue()); } }); // 3. 将Map.Entry添加到队列 queue.addAll(map.entrySet()); // 4. 遍历并验证排序结果 System.out.println("按值升序排序结果:"); while (!queue.isEmpty()) { Map.Entry<String, Integer> entry = queue.poll(); System.out.println(entry.getKey() + " -> " + entry.getValue()); } } } ``` ### 关键实现步骤解析 1. **创建原始 Map** ```java Map<String, Integer> map = new HashMap<>(); map.put("A", 30); map.put("B", 10); // ... 添加更多条目 ``` 2. **定义匿名 Comparator** ```java new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) { // 指定排序规则 return Integer.compare(e1.getValue(), e2.getValue()); // 按值升序 } } ``` - 按值升序:`Integer.compare(e1.getValue(), e2.getValue())` - 按值降序:`Integer.compare(e2.getValue(), e1.getValue())` - 按键排序:`e1.getKey().compareTo(e2.getKey())` 3. **初始化优先队列** ```java PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(/* 匿名Comparator */); ``` 4. **添加 Map.Entry 条目** ```java queue.addAll(map.entrySet()); // 一次性添加所有条目 ``` 5. **检索有序结果** ```java while (!queue.isEmpty()) { Map.Entry<String, Integer> entry = queue.poll(); System.out.println(entry.getKey() + " -> " + entry.getValue()); } ``` ### 输出结果示例 ``` 按值升序排序结果: B -> 10 D -> 20 A -> 30 C -> 50 ``` ### 排序规则修改示例 1. **按值降序排序** ```java return Integer.compare(e2.getValue(), e1.getValue()); // 值降序 ``` ``` 输出: C -> 50 A -> 30 D -> 20 B -> 10 ``` 2. **按键字母顺序排序** ```java return e1.getKey().compareTo(e2.getKey()); // 键升序 ``` ``` 输出: A -> 30 B -> 10 C -> 50 D -> 20 ``` ### 性能与注意事项 1. **时间复杂度**:入队 $O(\log n)$,出队 $O(\log n)$,堆顶访问 $O(1)$ [^4] 2. **线程安全**:`PriorityQueue` 非线程安全,多线程环境需用 `PriorityBlockingQueue` 3. **条目修改**:修改队列中条目值后需重新建堆(Java 未提供自动更新) 4. **空值处理**:队列不支持 `null` 元素,否则抛出 `NullPointerException` 该方法可用于: 1. Top K 问题(如找出值最大的10个条目) 2. 按自定义规则处理映射数据 3. 实现基于优先级的事件处理系统
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值