文章目录
在线选举
在选举中,第 i 张票是在时间为 times[i] 时投给 persons[i] 的。
现在,我们想要实现下面的查询函数: TopVotedCandidate.q(int t) 将返回在 t 时刻主导选举的候选人的编号。
在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。
persons:[0,1,1,0,0,1,0]
times:[0,5,10,15,20,25,30]
大致意思为:第0分钟给person[0]即0号投票,第5分钟给person[1]即1号投票。
测试数据为:3、12、25
时间为 3,票数分布情况是 [0],编号为 0 的候选人领先。
时间为 12,票数分布情况是 [0,1,1],编号为 1 的候选人领先。
时间为 25,票数分布情况是 [0,1,1,0,0,1],编号为 1 的候选人领先(因为最近的投票结果是平局)。
class TopVotedCandidate {
public int[] persons;
public int[] times;
public int[] dp;
public TopVotedCandidate(int[] persons, int[] times) {
this.persons = persons;
this.times = times;
//构建每时每刻的leader数组
HashMap<Integer,Integer> hashMap = new HashMap<>();
dp = new int[persons.length];
int maxCount = 0;
//当前的最多票数
int curLeader = 0;
//当前时刻当选者
for (int i = 0; i < dp.length; i++) {
int value = hashMap.getOrDefault(persons[i], 0);
//获取哈希表中该person的选票
hashMap.put(persons[i], ++value);
if (value >= maxCount) {
//如果该person的选票现在大于等于maxCount
maxCount = value;
curLeader = persons[i];
}
dp[i] = curLeader;
//当这次person的选票不足以达到maxCount时,dp[i] = curLeader
}
}
public int q(int t) {
int n = times.length - 1;
//寻找times数组中小于等于t的最右元素
int lo = 0, hi = n;
while (lo < hi) {
int mi = (lo + hi + 1) >> 1;
if (times[mi] <= t) lo = mi;
else hi = mi - 1;
}
//假设现在是12的时间,那么此时lo和hi指向2索引
//将索引对应到persons数组中
return dp[lo];
}
}
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate obj = new TopVotedCandidate(persons, times);
* int param_1 = obj.q(t);
*/