本文涉及的基础知识点
C++二分查找
LeetCode911. 在线选举
给你两个整数数组 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
预处理+二分查找
按顺序处理各票数,cnt记录当前各候选人的票数, top记录当前时间得票最高的候选人。当前候选人的票数 >= 当前最高票数,更换top。
 tops 记录各top。
 由于查询所在时间可能没有投票,所有不能it = lower_bound。
 必须it = upper_bound。 --it。
 构造函数(预处理)时间复杂度:O(n)。
 查询复杂度:O(logn)
代码
核心代码
class TopVotedCandidate {
		public:
			TopVotedCandidate(vector<int>& persons, vector<int>& times) {
				vector<int> cnts(persons.size());
				int top = 0;
				for (int i = 0; i < persons.size(); i++) {
					auto& tmp = cnts[persons[i]];
					tmp++;
					if (tmp >= cnts[top]) {
						top = persons[i];
					}
					m_tops.emplace_back(top);
				}
				m_times = times;
			}
			int q(int t) {
				auto index = upper_bound(m_times.begin(), m_times.end(),t)-m_times.begin();
				return m_tops[index-1];
			}
			vector<int> m_tops,m_times;
		};
 
单元测试
vector<int> persons, times;
		TEST_METHOD(TestMethod11)
		{
			persons = {0, 1, 1, 0, 0, 1, 0}, times={ 0, 5, 10, 15, 20, 25, 30 };
			TopVotedCandidate tv(persons, times);
			vector<int> inputs = { 3 ,  12 ,  25, 15,  24 ,  8 },outs;
			for (const auto& i : inputs) {
				auto res = tv.q(i);
				outs.emplace_back(res);
			}			
			AssertEx({ 0, 1, 1, 0, 0, 1 }, outs);
		}
 

扩展阅读
| 我想对大家说的话 | 
|---|
| 工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。 | 
| 学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作 | 
| 有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注 | 
| 闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。 | 
| 子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。 | 
| 如果程序是一条龙,那算法就是他的是睛 | 
| 失败+反思=成功 成功+反思=成功 | 
视频课程
先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
 https://edu.csdn.net/course/detail/38771
 如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
 https://edu.csdn.net/lecturer/6176
测试环境
操作系统:win7 开发环境: VS2019 C++17
 或者 操作系统:win10 开发环境: VS2022 C++17
 如无特殊说明,本算法用**C++**实现。



















