911. 在线选举
给你两个整数数组 persons 和 times 。在选举中,第 i 张票是在时刻为 times[i] 时投给候选人 persons[i] 的。
对于发生在时刻 t 的每个查询,需要找出在 t 时刻在选举中领先的候选人的编号。
在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。
实现 TopVotedCandidate 类:
TopVotedCandidate(int[] persons, int[] times) 使用 persons 和 times 数组初始化对象。
int q(int t) 根据前面描述的规则,返回在时刻 t 在选举中领先的候选人的编号。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/online-election
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TopVotedCandidate {
private List<Integer> tops;
private Map<Integer, Integer> voteCounts;
private int[] times;
public TopVotedCandidate(int[] persons, int[] times) {
tops = new ArrayList<>();
voteCounts = new HashMap<>();
voteCounts.put(-1, -1);
int top = -1;
for (int i = 0; i < persons.length; ++i) {
int p = persons[i];
voteCounts.put(p, voteCounts.getOrDefault(p, 0) + 1);
if (voteCounts.get(p) >= voteCounts.get(top)) {
top = p;
}
tops.add(top);
}
this.times = times;
}
public int q(int t) {
int ans = 0;
int l = 0, r = times.length - 1;
// 找到满足 times[l] <= t 的最大的 l
while (l <= r) {
int m = (l + r) >> 1;
if (times[m] <= t) {
ans = m;
l = m + 1;
} else {
r = m - 1;
}
}
return tops.get(ans);
}
}
心之所向,素履以往 生如逆旅,一苇以航
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】