题目链接 | 911. 在线选举 |
---|---|
思路 | 二分 |
题解链接 | [Python/Java/JavaScript/Go] 二分查找 |
关键点 | 理解题意:预处理 - 按照times 得出每个离散时刻下获胜者的person ;询问 - 二分查找到>t 的前一个时刻获胜者 |
时间复杂度 | \(O(n)\) |
空间复杂度 | \(O(n)\) |
代码实现:
class TopVotedCandidate:def __init__(self, persons: List[int], times: List[int]):n = len(times)self.times = timesself.answer = [-1] * ncnts = defaultdict(int)winner = Nonefor i, person in enumerate(persons):cnts[person] += 1if winner is None or cnts[person] >= cnts[winner]:winner = personself.answer[i] = winnerself.n = ndef q(self, t: int) -> int:left, right = -1, self.nwhile left + 1 < right:mid = (left+right) // 2if self.times[mid] <= t:left = midelse:right = midreturn self.answer[right - 1]
Python-标准库
class TopVotedCandidate:def __init__(self, persons: List[int], times: List[int]):n = len(times)self.times = timesself.answer = [-1] * ncnts = defaultdict(int)winner = Nonefor i, person in enumerate(persons):cnts[person] += 1if winner is None or cnts[person] >= cnts[winner]:winner = personself.answer[i] = winnerdef q(self, t: int) -> int:return self.answer[bisect_right(self.times, t) - 1]