Prove safety offer: Josephus problem, circle the number of the last remaining

Links: https://www.nowcoder.com/questionTerminal/11b018d042444d4d9ca4914c7b84a968
Source: Cattle-off network

Joseph problem is a very famous interesting question, namely the n people sit in a circle, clockwise by one of their number to begin. Then Countin by the first person, the number of people out to m. Now request is the last person out of the number.

Given two int n and m, the number of representatives of the game. Please return to the last man out of the number. N and m are less than or equal guarantee 1000.

Test Example:
53
Back: 4

Answer:
Links: https://www.nowcoder.com/questionTerminal/11b018d042444d4d9ca4914c7b84a968
Source: Cattle-off network

The number n of the individual to 0 ~ n-1, and deletion of the process were analyzed.
The first number is deleted (m-1)% n, denoted as k, the remaining number (0,1, ..., k-1 , k + 1, ..., n-1), the next start deleting when the sequence is (k + 1, ..., n -1,0,1, ... k-1).
It represents the final result of deleting from the start (0 ~ n-1) with f (n, m).
The final result represents a portion from the (k + 1, ..., n -1,0,1, ... k-1) with q (n-1, m) .
Then f (n, m) = q (n-1, m).

Following the (k + 1, ..., n -1,0,1, ... k-1) is converted to (0 ~ n-2) in the form, i.e.,
k + 1 corresponding to 0
K for 1 + 2
...
corresponding to k-1 n-2
conversion function is set to p (x) = (xk- 1)% n, p (x) is the inverse function p ^ (x) = (x + k + 1)% n.
Then f (n, m) = q (n-1, m) = p ^ (f (n-1, m)) = (f (n-1, m) + k + 1)% n, and because k = (m-1)% n .
f (n, m) = ( f (n-1, m) + m)% n;

The final recursion relations formula
F (. 1, m) = 0; (n-=. 1)
F (n-, m) = (F (n--. 1, m) + m) n-%; (n->. 1)

链接:https://www.nowcoder.com/questionTerminal/11b018d042444d4d9ca4914c7b84a968
来源:牛客网

import java.util.*;
 
public class Joseph {
    /*
     * 编号为(0~n-1)
     */
    public int getResult(int n, int m) {
        if (n < 0 || m < 0) {
            return -1;
        }
        int last = 0;
        for(int i=2;i<=n;++i){
            last = (last+m)%i;
        }
        // 因为实际编号为(1~n)
        return (last+1);
    }
}

python code:
did not quite understand the principle of going back to look thoroughly get to know


# -*- coding:utf-8 -*-
class Solution:
    def LastRemaining_Solution(self, n, m):
        # write code here
        if not m or not n:
            return -1
        res = range(n)
        i = 0
        while len(res)>1:
            i = (m+i-1)%len(res)
            res.pop(i)
        return res[0]

Guess you like

Origin blog.csdn.net/Leia21/article/details/89925646