解法一:字典
看到题,啪的一下就出来了,但是做的其实不好。条件太多,挺笨的。
class Solution:
def predictPartyVictory(self, senate: str) -> str:
d = [0, 0]
tp_ct = [0, 0]
tmp = ''
while True:
for s in senate:
if s == 'R':
if d[1] > 0:
d[1] -= 1
else:
d[0] += 1
tmp += 'R'
tp_ct[0] += 1
else:
if d[0] > 0:
d[0] -= 1
else:
d[1] += 1
tmp += 'D'
tp_ct[1] += 1
if tp_ct[0] == 0:
return "Dire"
elif tp_ct[1] == 0:
return "Radiant"
# update ds
tp_ct = [0, 0]
senate = tmp
tmp = ''
解法二:队列
最快的解法是用两个队列,分别记录两个议院的索引,重新入队时加上数组长度,比较刚开始两个元素的大小 即可确定哪个移除,哪个重新入队。是非常高效的解法。
其中,直接用当前索引加数组长度插入是可行的,因为在前面的元素一定会在前面插入,但在实际应用时要防止数值溢出。
from collections import deque
class Solution:
def predictPartyVictory(self, senate: str) -> str:
R, D = deque(), deque()
for i, s in enumerate(senate):
if s == 'R': R.append(i)
else: D.append(i)
while D and R:
d, r = D.popleft(), R.popleft()
if d < r: D.append(d+len(senate))
else: R.append(r+len(senate))
if D: return "Dire"
return "Radiant"