给定一系列给定时间给某人投票,求给定的时间点是谁胜出。
sol:
保存在投票的时间点胜出者,然后根据询问的时间点二分出答案
class TopVotedCandidate {
int len;
int[][] arr;
public TopVotedCandidate(int[] persons, int[] times) {
len = persons.length;
int maxCnt = 0;
int[] cnt = new int[5010];
arr = new int[len][2];
int lastWin = 0;
for (int i = 0; i < len; i++) {
cnt[persons[i]]++;
if (cnt[persons[i]] >= maxCnt) {
arr[i] = new int[]{times[i], persons[i]};
lastWin = persons[i];
maxCnt = cnt[persons[i]];
} else {
arr[i] = new int[]{times[i], lastWin};
}
}
}
public int q(int t) {
int l = 0;
int r = arr.length;
if (t >= arr[r-1][0]) {
return arr[r - 1][1];
}
while (l + 1 < r) {
int mid = (l + r) / 2;
if (arr[mid][0] == t) return arr[mid][1];
if (arr[mid][0] > t) {
r = mid;
} else {
l = mid;
}
}
return arr[l][1];
}
}