LeetCode-面试题62. 圆圈中最后剩下的数字

圆圈中最后剩下的数字

LeetCode-面试题62. 圆圈中最后剩下的数字_第1张图片

经典约瑟夫环问题
f ( n , m ) f(n,m) f(n,m)输出的是最后结点的index,则根据规律我们有
f ( n ) = { 0 , n = 1 ( ( m % n ) + f ( n − 1 , m ) ) % n , e l s e f(n)= \begin{cases} 0,&n=1\\ ((m\%n)+f(n-1,m))\%n,&else \end{cases} f(n)={0,((m%n)+f(n1,m))%n,n=1else
递归

class Solution {
public:
    int lastRemaining(int n, int m) {
        if (n == 1) {
            return 0;
        }
        int x = lastRemaining(n - 1, m);

        return (m + x) % n;
    }
};

迭代

class Solution {
public:
    int lastRemaining(int n, int m) {
        int ret = 0;
        for (int i = 2; i <= n; i++) {
            ret = (m + ret) % i;
        }

        return ret;
    }
};

你可能感兴趣的:(LeetCode)