algorithm - 根据开始和结束时间对赛车手进行排名
问题描述
问题:您有比赛的开始时间、结束时间和参赛者的索引号。你需要告诉每个赛车手的排名。排名计算如下:如果赛车手 B 在赛车手 A 之后开始但在赛车手 A 之前完成,则赛车手 A 的排名增加 1。
示例输入:
Index Start Time End time
0 100 170
1 80 150
2 120 165
3 110 145
输出:
Index Rank
2 0
3 0
1 1
0 2
我知道我可以使用嵌套循环并对它们进行比较和排名,但仍然不能 100% 确定。有人可以帮助我在 O(n^2) 和 O(n log n) 的时间复杂度中为这个问题编写伪代码吗?提前致谢。
解决方案
Index Start Time End time
0 100 170
1 80 150
2 120 165
3 110 145
按时间升序的所有实例排序。
(80, "start", 1)
(100, "start", 0)
(110, "start", 3)
(120, "start", 2)
(145, "end", 3)
(150, "end", 1)
(165, "end", 2)
(170, "end", 0)
遍历时间列表:
80:
current_racers = {1}
100:
current_racers = {1, 0}
110:
current_racers = {1, 0, 3}
120:
current_racers = {1, 0, 3, 2}
145:
current_racers = {1, 0, X, 2}
Racers 1 and 0 started
before racer 3 so their rank
increases by 1 when 3 is removed.
150:
current_racers = {X, 0, X, 2}
No racers started before racer
1 so no other ranks are changed
when they are removed.
165:
current_racers = {X, 0, X, X}
Racer 0 is before racer 2
so their rank is increased
when racer 2 is removed.
Ranks
0: 2
1: 1
2: 0
3: 0
在遍历期间,将竞速者插入为范围更新和点查询而安排的 fenwick 树中。(我猜“插入”只是将它们的索引记录在树中。树本身只包含与其每个索引相关的等级。)
在下一个索引处插入起始赛车手,始终在最后一次插入之前。当比赛结束时,输出存储在其索引处的排名,并将区间 [0, current_racer) 增加一。它们留在树上并不重要,因为它们不会再次影响赛车手。当树中只剩下一名赛车手时,输出他们的排名。
推荐阅读
- node.js - MERN APP - 如何使用上下文 api 在我的反应组件中访问带有 id 的 express 参数
- flutter - RangeError(RangeError(索引):无效值:只有有效值是0:1)
- javascript - 从 Javascript 中的其他两个数组构建一个新数组
- linux - 如何修复 CentOS WebPanel 无法在浏览器中运行但服务已启动并正在运行?
- javascript - 验证括号在字符串中是否正确配对。如果是,打印“有效”,否则打印“无效”(不带引号)
- javascript - 没有问题原因提示的错误 - 'ERROR @wdio/runner: Error'
- python - pip 崩溃:无法从“pip._vendor”导入名称“chardet”
- android - Flutter Build 失败,不在物理设备上运行
- python - 过滤熊猫列中的列表元素是否相同
- jhipster - 更新 Jhipster 应用程序的最佳策略是什么?