解法一:构造环型链表
时间复杂度o(nm),空间复杂度o(n)
class Node(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
head=Node(0)
tmp=head
for i in range(1,n):
tmp.next=Node(i)
tmp=tmp.next
tmp.next=head
while tmp.next != tmp:
for _ in range(m-1):
head=head.next
tmp=tmp.next
head=head.next
tmp.next=head
return tmp.val
解法二:递归
时间复杂度o(n),空间复杂度o(n)
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
return self.f(n,m)
def f(self,n,m):
if n == 0:
return 0
x=self.f(n-1,m)
return (m+x)%n