zoukankan      html  css  js  c++  java
  • Leetcode_面试题62. 圆圈中最后剩下的数字(约瑟夫环)

    经典的约瑟夫环,n个人排成一圈,第m个出队。

    递归
    code1

    class Solution {
    public:
        int f(int n,int m){
            if(n==1){
                //递归边界,最后一个
                return 0;
            }
            //先m出队,而最后留下的是在n-1个中排第f(n-1,m),在n个中就是排在m后面的第f(n-1,m)
            return (m+f(n-1,m))%n;
        }
        int lastRemaining(int n, int m) {
            return f(n,m);
        }
    };
    

    非递归
    code2

    class Solution {
    public:
        int lastRemaining(int n, int m) {
            int f=0;
            for(int i=2;i<=n;i++){
                f=(f+m)%i;
            }
            return f;
        }
    };
    
  • 相关阅读:
    fastjson 使用方法
    算法
    SHA算法
    MD5算法
    kindle推送服务
    DLL劫持
    Hook编程
    Hook技术
    权限验证
    虚拟机
  • 原文地址:https://www.cnblogs.com/zxcoder/p/12597226.html
Copyright © 2011-2022 走看看