每日一题-911. 在线选举_JavaScript
2021/12/11 17:19:42
本文主要是介绍每日一题-911. 在线选举_JavaScript,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
-
给你两个整数数组 persons 和 times 。在选举中,第 i 张票是在时刻为 times[i] 时投给候选人 persons[i] 的。
-
对于发生在时刻 t 的每个查询,需要找出在 t 时刻在选举中领先的候选人的编号。
-
在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。
实现 TopVotedCandidate 类:
TopVotedCandidate(int[] persons, int[] times) 使用 persons 和 times 数组初始化对象。
int q(int t) 根据前面描述的规则,返回在时刻 t 在选举中领先的候选人的编号。
示例:
输入:
[“TopVotedCandidate”, “q”, “q”, “q”, “q”, “q”, “q”]
[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]
输出:
[null, 0, 1, 1, 0, 0, 1]
解释:
TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);
topVotedCandidate.q(3); // 返回 0 ,在时刻 3 ,票数分布为 [0] ,编号为 0 的候选人领先。
topVotedCandidate.q(12); // 返回 1 ,在时刻 12 ,票数分布为 [0,1,1] ,编号为 1 的候选人领先。
topVotedCandidate.q(25); // 返回 1 ,在时刻 25 ,票数分布为 [0,1,1,0,0,1] ,编号为 1 的候选人领先。(在平局的情况下,1 是最近获得投票的候选人)。
topVotedCandidate.q(15); // 返回 0
topVotedCandidate.q(24); // 返回 0
topVotedCandidate.q(8); // 返回 1
提示:
1 <= persons.length <= 5000
times.length == persons.length
0 <= persons[i] < persons.length
0 <= times[i] <= 10^9
times 是一个严格递增的有序数组
times[0] <= t <= 10^9
每个测试用例最多调用 10^4 次 q
程序代码
/** * @param {number[]} persons * @param {number[]} times */ var TopVotedCandidate = function(persons, times) { this.map=new Map() this.times=times let top=-1 this.map.set(-1,-1) this.tops=[] for(let i=0;i<persons.length;i++){ if(!this.map.has(persons[i])){ this.map.set(persons[i],0) }else{ this.map.set(persons[i],this.map.get(persons[i])+1) } if(this.map.get(persons[i])>=this.map.get(top)){ top=persons[i] } this.tops.push(top) } }; TopVotedCandidate.prototype.q = function(t) { let i=0 let j=this.times.length - 1 while(i<j) { let mid=i+Math.floor((j-i+1)/2); if (this.times[mid]<= t) { i=mid; } else { j=mid-1; } } return this.tops[i]; };
这篇关于每日一题-911. 在线选举_JavaScript的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?