"Sword Finger Offer" Brush Question Series-(56) The last remaining number in the circle

topic

The n numbers of 0,1,n-1 are arranged in a circle, starting from the number 0, and deleting the mth number from this circle each time. Find the last number remaining in the circle.

For example, the 5 numbers 0, 1, 2, 3, and 4 form a circle. Each time the third number is deleted from the number 0, the first 4 numbers to be deleted are 2, 0, 4, and 1, so at the end The remaining number is 3.

Code

class Solution:
    def lastRemaining(self, n: int, m: int) -> int:
        if n<1 or m<1: return None
        f=0
        for i in range(2,n+1):
            f=(f+m)%i
        return f

the complexity

Time complexity: O(n), there are nnn function values ​​to be solved.
Space complexity: O(1), only constant variables are used.

Guess you like

Origin blog.csdn.net/weixin_44776894/article/details/107444720