题解 | #孩子们的游戏(圆圈中最后剩下的数)#
孩子们的游戏(圆圈中最后剩下的数)
http://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6
两种方法 一种模拟法 一种使用约瑟夫环得到的公式求解 模拟法
class Solution:
def LastRemaining_Solution(self , n: int, m: int) -> int:
# write code heredef lastRemaining(n,m):
# if n == 0:
# return 0
# return (self.LastRemaining_Solution(n-1,m)+m)%n
约瑟夫环法:
class Solution:
def LastRemaining_Solution(self , n: int, m: int) -> int:
if n < 1:
return -1
con = list(range(n))
final = -1
start = 0
while con:
k = (start+m-1)%n
final = con.pop(k)
n -= 1
start = k
return final