
题目分析
- 根据题意我们需要统计在t时刻获得选票最多的候选人,这里我们对数据进行预处理,在每次增加选票时记录当前的最高票数与候选人id,如果获得选票最多的候选人发生变化我们向source中插入当前时间加候选人id的信息。在每次查询t时刻获得选票最多的候选人时,我们用二分法对source进行查询,查找第一个<=t时间的信息。
代码
let TopVotedCandidate = function (persons, times) {
const map = new Map();
let max = -1;
this.source = [];
for (let i = 0, { length } = times; i < length; ++i) {
let v = map.get(persons[i]) || 0;
if (++v >= max) {
this.source.push({ time: times[i], id: persons[i] });
max = v;
}
map.set(persons[i], v);
}
};
TopVotedCandidate.prototype.q = function (t) {
const { source } = this;
let left = 0;
let right = source.length - 1;
while (left <= right) {
let mid = left + ((right - left) >> 1);
if (source[mid].time < t) {
left = mid + 1;
} else if (source[mid].time > t) {
right = mid - 1;
} else {
return source[mid].id;
}
}
return source[right].id;
};