哈希算法题目:设计一个基于哈希的在线选举系统
字数 774 2025-11-02 10:11:21
哈希算法题目:设计一个基于哈希的在线选举系统
题目描述
设计一个在线选举系统,用于在选举过程中实时统计候选人的得票数,并支持快速查询当前领先的候选人。系统需要支持以下操作:
vote(candidate, timestamp):在给定时间戳为某个候选人投票getLeadingCandidate(timestamp):查询在某个时间戳或之前时间点的领先候选人
如果有平票情况,返回最近获得投票的候选人。
解题过程
步骤1:理解问题需求
这个系统需要处理按时间顺序到来的投票,并能在任意时间点查询当时的选举结果。关键点:
- 投票带有时间戳,且时间戳是递增的
- 需要快速查询历史时间点的领先者
- 平票时选择最近获得投票的候选人
步骤2:数据结构设计分析
我们需要两种核心数据结构:
- 票数统计:需要快速更新和查询候选人的得票数
- 时间线记录:需要记录每个时间点的领先者,以便快速查询历史结果
步骤3:具体实现方案
方案1:哈希表 + 二分查找
class OnlineElection:
def __init__(self):
# 存储每个候选人的总票数
self.vote_counts = {}
# 存储时间戳和对应的领先者
self.leading_at_time = []
# 记录当前最大票数
self.max_votes = 0
# 记录当前领先者
self.current_leader = None
def vote(self, candidate: str, timestamp: int) -> None:
# 更新候选人票数
self.vote_counts[candidate] = self.vote_counts.get(candidate, 0) + 1
current_votes = self.vote_counts[candidate]
# 判断是否需要更新领先者
if (current_votes > self.max_votes or
(current_votes == self.max_votes and
self.leading_at_time and
self.leading_at_time[-1][1] != candidate)):
self.max_votes = current_votes
self.current_leader = candidate
# 记录时间点和对应的领先者
self.leading_at_time.append((timestamp, self.current_leader))
def getLeadingCandidate(self, timestamp: int) -> str:
# 使用二分查找找到小于等于给定时间戳的最大时间点
left, right = 0, len(self.leading_at_time) - 1
result = None
while left <= right:
mid = (left + right) // 2
if self.leading_at_time[mid][0] <= timestamp:
result = self.leading_at_time[mid][1]
left = mid + 1
else:
right = mid - 1
return result
步骤4:算法优化分析
上述方案的时间复杂度:
vote操作:O(1)时间更新票数,O(1)时间记录领先者getLeadingCandidate:O(log n)时间进行二分查找
空间复杂度:O(n),其中n是投票次数
步骤5:处理边界情况
考虑几种特殊情况:
- 首次投票:系统初始化时没有领先者
- 平票处理:严格按照"最近获得投票"规则
- 查询时间点早于所有投票:应返回None或适当默认值
改进版本处理平票:
class OnlineElection:
def __init__(self):
self.vote_counts = {}
self.time_records = [] # 存储(时间戳, 领先者, 最大票数)
self.last_vote_time = {} # 记录每个候选人最后投票时间
def vote(self, candidate: str, timestamp: int) -> None:
# 更新最后投票时间
self.last_vote_time[candidate] = timestamp
# 更新票数
self.vote_counts[candidate] = self.vote_counts.get(candidate, 0) + 1
current_votes = self.vote_counts[candidate]
# 确定当前领先者
if not self.time_records:
# 第一次投票
leader = candidate
max_votes = current_votes
else:
last_leader, last_max_votes = self.time_records[-1][1], self.time_records[-1][2]
if current_votes > last_max_votes:
leader = candidate
max_votes = current_votes
elif current_votes == last_max_votes:
# 平票时选择最后投票的候选人
if self.last_vote_time[candidate] > self.last_vote_time[last_leader]:
leader = candidate
else:
leader = last_leader
max_votes = current_votes
else:
leader = last_leader
max_votes = last_max_votes
self.time_records.append((timestamp, leader, max_votes))
步骤6:实际应用场景
这种设计适用于:
- 实时选举统计系统
- 股票市场领导者追踪
- 实时排行榜系统
- 任何需要历史状态查询的计数系统
关键要点总结
- 使用哈希表进行O(1)时间的票数更新
- 维护时间线记录支持历史查询
- 二分查找优化查询效率
- 正确处理平票等边界情况
- 权衡时间复杂度和空间复杂度