编程语言
首页 > 编程语言> > 每日一题-911. 在线选举_JavaScript

每日一题-911. 在线选举_JavaScript

作者:互联网

实现 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];
};

标签:map,JavaScript,topVotedCandidate,times,persons,一题,TopVotedCandidate,911,候选人
来源: https://blog.csdn.net/weixin_45344430/article/details/121874193