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
]
posted @   WrRan  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示