标签:Day28 候选人 int topVotedCandidate times persons 一题 TopVotedCandidate 在线
给你两个整数数组 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] <= 109
times 是一个严格递增的有序数组
times[0] <= t <= 109
每个测试用例最多调用 104 次 q来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/online-election
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。[0,1,1,0,0,1,0], [0,5,10,15,20,25,30]
上面的输入表示:
第 0 分钟投给 0 号; 第 5 分钟投给 1 号; 第 10 分钟投给 1 号;
class TopVotedCandidate {
int[] times;
int[] win;
int[] persons;
public TopVotedCandidate(int[] persons, int[] times) {
this.times=times;
this.persons=persons;
win=new int[persons.length];//储存time[i]时的获胜者
Map<Integer, Integer> personElect =new HashMap<>();//候选人编号——其选票数
int max=0 ,index=-1;
for(int i=0;i<persons.length;i++){
int person=persons[i];
personElect.put(person,personElect.getOrDefault(person,0)+1);
if(personElect.get(person)>=max){//获得当前当前最大获票数及其对应编号
max=personElect.get(person);
index=person;
}
win[i]=index;
}
}
public int q(int t) {
int l=0;
int r=persons.length-1;
while(l<=r){// 二分法,找小等于t的最近时间
int mid=(l+r)/2;
if(times[mid]>t){
r=mid-1;
}else if(times[mid]<=t){
l=mid+1;
}
}
return win[r];
}
}
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate obj = new TopVotedCandidate(persons, times);
* int param_1 = obj.q(t);
*/
标签:Day28,候选人,int,topVotedCandidate,times,persons,一题,TopVotedCandidate,在线 来源: https://blog.csdn.net/m0_62256641/article/details/122669094
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。