LeetCode#1086. High Five

LeetCode 参考 Java版本 LeetCode 400题目 Java版本 (LeetCode is the platform to help you enhance your skills, expand your knowledge and prepare for technical interviews.) 立即下载

1086. High Five

Example 1:

Input: items =
[[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
Output: [[1,87],[2,88]] Explanation: The student with ID = 1 got
scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 +
92 + 91 + 87 + 65) / 5 = 87. The student with ID = 2 got scores 93,
97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 +
76) / 5 = 88.6, but with integer division their average converts to
88.

Approach 1: Using Sorting

Intuition

Since we have to take into account the top 5 values corresponding to each id, we can sort the items array, first based on the id and next based on the score, i.e. items will be sorted based on increasing order of their ids. In case we have a tie for the value of ids, the items are then sorted based on decreasing order of the scores.

Algorithm

We can implement the idea for Approach 1 simply by having a custom comparator, which sorts the array based on the increasing order of ids and in case of tie, with the decreasing order of scores.

Below is the implementation of this approach.

[Java]

class Solution {

    private int K;

    public int[][] highFive(int[][] items) {
        this.K = 5;
        Arrays.sort(
                items,
                new Comparator<int[]>() {
                    @Override
                    public int compare(int[] a, int[] b) {
                        if (a[0] != b[0])
                            // item with lower id goes first
                            return a[0] - b[0];
                        // in case of tie for ids, item with higher score goes first
                        return b[1] - a[1];
                    }
                });
        List<int[]> solution = new ArrayList<>();
        int n = items.length;
        int i = 0;
        while (i < n) {
            int id = items[i][0];
            int sum = 0;
            // obtain total using the top 5 scores
            for (int k = i; k < i + this.K; ++k)
                sum += items[k][1];
            // ignore all the other scores for the same id
            while (i < n && items[i][0] == id)
                i++;
            solution.add(new int[] {id, sum / this.K});
        }
        int[][] solutionArray = new int[solution.size()][];
        return solution.toArray(solutionArray);
    }
}
Approach 2: Using Map and Max Heap

Intuition

We can notice here that the only scores that contribute towards the calculation of the average are the top 5 scores. Therefore, if we only need the top 5 scores for each of the id we can ignore the rest of the scores. This can be done using a max heap.

Algorithm

We can maintain a max heap of all the scores for every id. This way, we can simply obtain the top 5 scores for each of the id by obtaining the first 5 elements from the max heap (which are indeed the top 5). Additionally, we would also need a map where the id of the student will be used as the key (as we want scores for the same id to be clubbed together in the same max heap).

Note that we’ll be using an ordered map (or a tree map) in this case as we want the final output scores to be in sorted order (which we can obtain by directly iterating over the keys of the map).

Below is the implementation of this approach.
[Java]

class Solution {
    private int K;

    public int[][] highFive(int[][] items) {
        this.K = 5;
        TreeMap<Integer, Queue<Integer>> allScores = new TreeMap<>();
        for (int[] item : items) {
            int id = item[0];
            int score = item[1];
            if (!allScores.containsKey(id))
                // max heap
                allScores.put(id, new PriorityQueue<>((a,b) -> b - a));
            // Add score to the max heap
            allScores.get(id).add(score);
        }

        List<int[]> solution = new ArrayList<>();

        for (int id : allScores.keySet()) {
            int sum = 0;
            // obtain the top k scores (k = 5)
            for (int i = 0; i < this.K; ++i)
                sum += allScores.get(id).poll();
            solution.add(new int[] {id, sum / this.K});
        }
        int[][] solutionArray = new int[solution.size()][];
        return solution.toArray(solutionArray);
    }
}
Approach 3: Using Map and Min Heap

Intuition

Till now, we have used a max heap using which we can obtain the top 5 elements by simply popping them out of the max heap one by one. However, for this, we have to store all the scores for each id in the max heap. This is inefficient. Since we are only interested in obtaining the top 5 scores, we do not need to store all the scores.

This can be made efficient using a min heap. In this approach, we will keep a min heap of the top 5 scores for each of the id. Whenever we encounter a score for an id, which is greater than the minimum score present in the min heap of that particular id, we update our min heap by adding the current score and removing the minimum score. This way, the size of the min heap never exceeds 5 which is a much more efficient implementation than keeping all the scores in the heap.

Algorithm

For each of the id, we can keep inserting all the scores in the corresponding min heap. Whenever we reach a state where the size of the min heap exceeds 5, we’ll simply remove the minimum element from the min heap, thereby making sure that the size of the min heap never exceeds 5.

Below is the implementation of this approach.
[Java]

class Solution {
    private int K;

    public int[][] highFive(int[][] items) {
        this.K = 5;
        TreeMap<Integer, Queue<Integer>> allScores = new TreeMap<>();
        for (int[] item : items) {
            int id = item[0];
            int score = item[1];
            if (!allScores.containsKey(id))
                allScores.put(id, new PriorityQueue<>());
            // insert the score in the min heap
            allScores.get(id).add(score);
            // remove the minimum element from the min heap in case the size of the min heap exceeds 5 
            if (allScores.get(id).size() > this.K)
                allScores.get(id).poll();
        }

        List<int[]> solution = new ArrayList<>();

        for (int id : allScores.keySet()) {
            int sum = 0;
            // min heap contains the top 5 scores
            for (int i = 0; i < this.K; ++i)
                sum += allScores.get(id).poll();
            solution.add(new int[] {id, sum / this.K});
        }
        int[][] solutionArray = new int[solution.size()][];
        return solution.toArray(solutionArray);
    }
}
Approach 4: Using priority queue for each id

[Python]

class Solution:
    def highFive(self, items: List[List[int]]) -> List[List[int]]:
        d = collections.defaultdict(list)
        
        for idx, val in items:
            heapq.heappush(d[idx], val)
            
            if len(d[idx]) > 5:
                heapq.heappop(d[idx])
        
        res = [[i, sum(d[i]) // len(d[i])] for i in sorted(d)]
        
        return res
Approach 5: Running Length Encoding

first sort reversely by id and score, and then calculate average for each id
[Python]

class Solution:
    def highFive(self, items: List[List[int]]) -> List[List[int]]:
        items.sort(reverse=True)
        
        res = []
        curr = []
        idx = items[0][0]
        
        for i, val in items:
            if i == idx:
                if len(curr) < 5:
                    curr.append(val)
            else:
                res.append([idx, sum(curr) // len(curr)])
                curr = [val]
                idx = i
        
        res.append([idx, sum(curr) // len(curr)])
        
        res = res[::-1]
        
        return res
Approach 6: Using priority queue for each id

[Python]

class Solution(object):
    def highFive(self, items):
        res = {}
        for i in items:
            if i[0] in res:
                res[i[0]].append(i[1])
                res[i[0]] = sorted(res[i[0]], reverse=True)
            else:
                res[i[0]] = [i[1]]
        return [[i,sum(res[i][:5])/5] for i in res.keys()]  
sentaurus浪涌仿真sdevice代码解释(4) 9. `Plot(FilePrefix="Surge_n@node@" time=(Range=(0 @<0+10E-3>@) Intervals=10) NoOverWrite)`:设置了一个绘图过程,用于在瞬态分析过程中绘制结果,文件名前缀为`Surge_n@node@`,时间范围从0到`10E-3`秒,每隔10个时间点绘制一次,且不覆盖之前的结果。同样设置了最大迭代次数和线搜索阻尼系数。这个过程将模拟从`0`到`10E-3`秒内器件的行为,并且会在不同的时间点记录和绘制电流和电势的数据。 阅读详情

相关推荐

香橙派5b 移植 imx415

修改设备树,以为例,关闭ov13855,添加imx4151;0;1;0;1;0;1;0;1;0;1;0;1;0;以此类推,修改三个dtsi。

ChenYX的博客 4535

【Leetcode】1086. High Five

题目地址: https://leetcode.com/problems/high-five/ 给定一个二维数组,每一行代表某个学生的某一科目分数,第一个数字是学生id,第二个数字是分数。要求返回一个数组,存储每个学生最高的555门课的平均分(返回整型即可),并且数组要按学生id排序。 思路是哈希表 + 堆。哈希表key存id,value存一个堆,堆里存id对应的学生的最高无门课的分数。代码如下: import java.util.Map; import java.util.PriorityQueue; im

数学、算法爱好者的博客 434

设置Solidworks导出文件的坐标系,stl坐标系平移

使用solidworks输出的模型坐标不再原点,怎么平行坐标系,这个方法很简单

weixin_45650767的博客 1万+

【LeetCode - 1086】前五科的均分

【简单】排序、数组、哈希表

学哥斌的博客 772

【AUTOSAR-COM】Transmission Mode 和 Transfer Property

1.COM模块的基本概念 首先在描述Transmission Mode 和 Transfer Property之前,有必要对COM模块的基本处理有一个直观的理解,我所描述的和对概念理解的也不一定完全正确。 Signal:指的是通信协议中的,一条报文中所保存的若干信号。 I-PDU:至少在COM模块中,可以理解为一条报文。 上图是在CANdb软件中编辑一个报文的Layout的界面,可以很形象的将I-PDU对等为这里的一条Message,而Signal就是需要在Message中需要摆放的Signal

tim_hoven的博客 4635

硬件单板类机考复习提纲

6、 功率晶体管低导通损耗时处于的状态(饱和状态、放大状态、截止状态)(放大器的采样频率特性)总结:元器件特性(电阻、电容、二极管、三极管、晶体、晶振、MOS、磁珠等)信号质量问题产生根因(单调性、边沿过缓、毛刺、回沟、抖动等)3、 几种电容容量范围大小(超级电容、钽电容、陶瓷电容、铝电容)66、背板连接器接触设计的接触顺序(先导向、再地针、最后信号针)28、逻辑电平接口的特性(CMOS、TTL、ECL、PECL)76、差分电平(lvpecl、RS-422/485、cml)

2303_79562407的博客 1万+

LeetCode题解(1086):前五科的均分(Python)

题目:原题链接(简单) 标签:哈希表、堆、排序、数组 解法 时间复杂度 空间复杂度 执行用时 Ans 1 (Python) O(N)O(N)O(N) O(N)O(N)O(N) 28ms (100.00%) Ans 2 (Python) Ans 3 (Python) 解法一: class Solution: def highFive(self, items: List[List[int]]) -> List[List[int]]: # 统计

长行 554

Java对接快递鸟,查询快递物流信息

根据用户输入的订单号,我们的后台识别订单号并根据快递鸟查询快递API接口,实现自动查询的功能。下面是java版本的根据单号查询物流跟踪信息的详细示例代码。只需要下载就可以运行,(自己需要简单的修改)注:登录快递鸟用户管理后台后获得。登录快递鸟用户管理后台。

Roc的博客 958

LeetCode 1086. 前五科的均分(map + 优先队列)

文章目录1. 题目2. 解题 1. 题目 给你一个不同学生的分数列表,请按 学生的 id 顺序 返回每个学生 最高的五科 成绩的 平均分。 对于每条 items[i] 记录, items[i][0] 为学生的 id,items[i][1] 为学生的分数。 平均分请采用整数除法计算。 示例: 输入:[[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]] 输出:[[1,87],[2,88]] 解释: id

Michael是个半路程序员 2164

STM32 使用IQmath实现SVPWM

文章目录SVPWMIQMATHIQmathLib测试部分程序附件 SVPWM SVPWM是空间矢量脉宽调制(Space Vector Pulse Width Modulation)的简称,通常由三相逆变器的六个功率开关管组成,经过特定的时序和换相所所产生的脉冲宽度调制波,最终输出的波形可能会十分接近理想的正弦波形。 具体如下图所示;左侧为复平面,即空间矢量,右侧为时域的正弦波形; 关于SVPWM原理的文章非常多,这里可以推荐一下网上一个非常不错的教程《SVPWM的原理及法则推导和控制算法详解第五修改版》,

一名热爱技术的工程师的博客。分享技术干货,记录美好生活。永远相信美好的事情即将发生。 2万+

【测开求职】面试题:操作系统 吐血整理

本篇文章是笔者为准备研究生复试和校招而写,因此主要针对问答,注重理解,而不在于细节计算。涵盖考研范围内的所有知识内容,读者可以先查看上面的链接走一遍操作系统的整体框架结构。其中,重点难点以及易混淆的知识点,笔者用其他文章进行了详述,在知识点处贴好了链接,有需要的可以查阅。另外操作系统在校招中有非常明显的重点,一般情况下只会考察进程管理,内存管理,和设备管理,且这三者考察频率依次递减,文件管理基本不会考察。

vector的博客 7908

LeetCode-Python-1086. 前五科的均分

给你一个不同学生的分数列表,请按学生的 id顺序返回每个学生最高的五科成绩的平均分。 对于每条items[i]记录,items[i][0]为学生的 id,items[i][1]为学生的分数。平均分请采用整数除法计算。 示例: 输入:[[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[...

Keep Coding 2205

基于Cesium实现,动态水面+大坝排水动画

一、绘制面状水域,使用水波纹理,进行渲染,水体透明,可以看到底色。三、使用粒子系统,将喷泉改变方向,加上重力设置,实现排水动画。二、绘制线状三维体,用作模拟大坝拦截效果。四、最后,模拟水位上升,进行淹没分析,

一醉千秋的专栏 1420

Leetcode-1086 high five(前五科的均分)

1 #define _for(i,a,b) for(int i = (a);i < b;i ++) 2 struct cmp 3 { 4 bool operator() (int a,int b) 5 { 6 return a>b; 7 } 8 }; 9 class Solution 10 { 11 ...

weixin_30278237的博客 470

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

leetcode 算法题1086 (简单286) 前五科的均分

leetcode 算法题1086 (简单286) 前五科的均分 题目介绍 给你一个不同学生的分数列表, 请按 学生的 id 顺序 返回每个学生 最高的五科 成绩的 平均分。 对于每条 items[i] 记录, items[i][0] 为学生的 id,items[i][1] 为学生的分数。 平均分...

FYuu95100的博客 1284

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

【LeetCode】1086. High Five 解题报告(C++)

作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法大根堆日期 题目地址:https://leetcode-cn.com/problems/high-five/ 题目描述 Given a list of scores of different students, return the ave...

负雪明烛 1744

leetcode 1086. 前五科的均分(C++)

给你一个不同学生的分数列表,请按学生的 id顺序返回每个学生最高的五科成绩的平均分。 对于每条items[i]记录,items[i][0]为学生的 id,items[i][1]为学生的分数。平均分请采用整数除法计算。 示例: 输入:[[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[...

qq_27060423的博客 4767

LC.1086. High Five

class Solution(object): def highFive(self, items): """ 这道题也可以转化为前K 大问题,分组后利用快排的思想 """ def getK(array, start, end, K): if start > end : ...

很吵请安静 427

Leetcode 1086. High Five Java 解法

先吐槽一下这个难度,咋也不能是easy啊,和其他easy的不在一个量级。 Given a list of scores of different students, return the average score of each student'stop five scoresinthe order of each student's id. Each entryitems[i]h...

YuanTheCoder的博客 1473

leetcode1086

1 class Solution: 2 def highFive(self, items: List[List[int]]) -> List[List[int]]: 3 n = len(items) 4 dic = {} 5 for item in items: 6 ids = item...

weixin_33819479的博客 321

leetcode-1086. 前五科的均分-C语言

/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume ...

SFFS 1340

leetcode——1086.前五科的均分

思路 按照题目要求对同一个学生科目成绩进行降序排序 对不同学生学号进行升序排序 根据学号的不同,对成绩数组进行遍历 代码 class Solution { public: static bool cmp(vector<int>& a, vector<int>& b) { if (a[0] == b[0]) return a[1] > b[1];//取高分科目 else

Dedication_的博客 294

Leet Code Python版本 持续更新

为什么写这篇博客呢,主要是督促自己能够一直走下去,而不是做一两道题就停止了而已,哈哈。。 Two_sum 此题核心是利用了map key的不重复性方便了查找,比较简单,不在多说 #!/usr/bin/python3 import numpy as np &amp;amp;quot;&amp;amp;quot;&amp;amp;quot; 1. Two Sum Given an array of integers, return indices of th

李龙生 736

LeetCode:HighFive

模拟题: #include<bits/stdc++.h> using namespace std; void printVec1(vector<int>& v); void printVec2(vector<vector<int>>& v); class Solution { struct Node{ int id; ...

ShellDawn的博客 364

High Five

There are two properties in the node student id and scores, to ensure that each student will have at least 5 points, find the average of 5 highest scores for each person. Have you met this ques

ncst 1145

LintCode 613: High Five (MinHeap)

High Five There are two properties in the node student id and scores, to ensure that each student will have at least 5 points, find the average of 5 highest scores for each person. Example Given res...

roufoo的博客 1537
上一篇: Pandas_AutoReport_财务自动化统计报表
下一篇: LeetCode#1474
AlfredaYu
博客等级 码龄8年 61粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值