题目
给你两个整数数组 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
方法
提前记录
class TopVotedCandidate {
private int[] persons;
private int[] times;
private Map<Integer,Integer> map = new HashMap<>();
private List<Integer> elected = new ArrayList<>();
public TopVotedCandidate(int[] persons, int[] times) {
this.persons = persons;
this.times = times;
map.put(-1,-1);
int cur = -1;
for(int i=0;i<persons.length;i++){
map.put(persons[i], map.getOrDefault(persons[i], 0)+1);
if(map.get(persons[i]) >= map.get(cur)){
cur = persons[i];
}
elected.add(cur);
}
}
public int q(int t) {
int index = 0;
for(int i=0;i<times.length;i++){
if(t == times[i]){
index = i;
break;
}else if(t < times[i]){
index = i-1;
break;
}else if(i == times.length-1){
index = times.length-1;
break;
}else{
continue;
}
}
return elected.get(index);
}
}
- 主要思路:在初始化类 TopVotedCandidate 时就记录下每个投票时刻,被选出的人的变化情况。
- 用 map记录每个被选举者的的票情况
- 遍历persons数组,每一个值就是一次投票行为,在每个值时都记录出:截止到当前投票行为时,谁会被选举上
- 具体判断逻辑:先将当前被投票的人,在map中的计数+1,然后与上一个cur也就是上一时刻当选者的票数对比,一旦比后者多或相同,都会更新cur为当前被投票人。然后存入elected列表中
- 初始化结束后,elected数组就代表每一次投票行为发生后,对应的当选者。
- 根据传入的t时刻遍历,查找出t时刻已经发生了多少次投票行为,就可以找到对应的当选者。
注意:
- 初始化时,map传入**(-1,-1),cur设为-1**,使得第一个数值能成功更新。
- 最后的q方法,也可以用二分查找出对应的投票行为次数,效率更高。