题目传送门
链接:https://leetcode-cn.com/problems/online-election/
题干
题解
每个测试用例会最多调用 10410^4104 次查询,每次查询时刻 ttt 时票数最多的人
可以知道,如果 t 时刻没有投票,那么时刻 t 的答案就是前一次投票时的答案
如果时刻 t 投票了,那么答案就是此次投票的答案
使用 upper_bound 函数查询大于 t 的时间序号 idx,times[idx-1] 时刻票数最多的人就是答案
预处理 res 和 times 数组的时间复杂度为 O(n),设查询次数为 x,查询复杂度为 O(xlogn)
Code
class TopVotedCandidate {
public:
int res[5005], n;
int times[5005];
TopVotedCandidate(vector<int>& persons, vector<int>& times) {
// 数组长度
n = times.size();
// cnts 记录每个候选人的票数
map<int, int> cnts;
// cur 是当前最高票数的人
int cur = -1;
for (int i = 0; i < n; i++) {
this -> times[i] = times[i];
cnts[persons[i]]++;
if (cur == - 1 || cnts[persons[i]] >= cnts[cur]) {
cur = persons[i];
}
// 记录当前时刻票数最多的人
res[i] = cur;
}
}
int q(int t) {
int idx = upper_bound(times, times + n, t) - times - 1;
return res[idx];
}
};
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate* obj = new TopVotedCandidate(persons, times);
* int param_1 = obj->q(t);
*/