1. 思路
认真审题,思考两个主要问题:
(1) 如何解决重新开始报数问题
(2) 如何解决周期问题
2. 代码
# -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
round = list(range(n))
index = -1
while len(round) > 1:
count = 0
while count < m:
count += 1
index += 1
# 考虑循环周期问题
if index == len(round):
index =0
round.pop(index)
# 1 2 3 4 5 当3被pop掉后,index要回退到2,相当于开头的-1重新开始
index -= 1
if round:
return round[0]
else:
return -1