中级农民
- 积分
- 183
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2022-4-7
- 最后登录
- 1970-1-1
|
感觉这个像是一个backtrack呀,回溯每一个人的投票,每次都从第一志愿一直选到最后。尤其按照“例子3”的描述,如果所有人的投票投不出结果,那就从后往前改(最后投票的先改自己的票),这正好符合了backtrack自底向上回溯的过程。
下面是我的实现,目前的三个测试用例是都可以过的,可以作为参考- from typing import List
- from collections import Counter
- result = None
- def q4(votes: List[List[int]]) -> int:
- backtrack(votes, Counter(), 0)
- return result
- def backtrack(votes: List[List[int]], counter: Counter, index: int) -> None:
- global result
- if result:
- return
- if index == len(votes):
- winner, count = max(counter.items(), key=lambda item: item[1])
- if count > len(votes) // 2:
- result = winner
- return
- for candidate in votes[index]:
- counter[candidate] += 1
- backtrack(votes, counter, index + 1)
- counter[candidate] -= 1
- votes = [ [1], [1], [2] ]
- print(q4(votes)) # 1
- votes = [ [1], [1], [2], [2], [3, 1] ]
- print(q4(votes)) # 1
- votes = [ [1, 2], [1, 2], [2, 1], [2, 3], [3, 1] ]
- print(q4(votes)) # 1
复制代码 |
|