911. 在线选举
| 题目链接 | 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 = times
self.answer = [-1] * n
cnts = defaultdict(int)
winner = None
for i, person in enumerate(persons):
cnts[person] += 1
if winner is None or cnts[person] >= cnts[winner]:
winner = person
self.answer[i] = winner
self.n = n
def q(self, t: int) -> int:
left, right = -1, self.n
while left + 1 < right:
mid = (left+right) // 2
if self.times[mid] <= t:
left = mid
else:
right = mid
return self.answer[right - 1]
Python-标准库
class TopVotedCandidate:
def __init__(self, persons: List[int], times: List[int]):
n = len(times)
self.times = times
self.answer = [-1] * n
cnts = defaultdict(int)
winner = None
for i, person in enumerate(persons):
cnts[person] += 1
if winner is None or cnts[person] >= cnts[winner]:
winner = person
self.answer[i] = winner
def q(self, t: int) -> int:
return self.answer[
bisect_right(self.times, t) - 1
]

浙公网安备 33010602011771号