Old Wei wins the offer to take you to learn --- Brush title series (46. Child's Play (circle last remaining number))

46. ​​Child's Play (circle last remaining number)

problem:

Children's Day each year, cow-off will prepare some small gifts to visit the orphanage children, this year is also true. As an experienced veteran off HF cattle, naturally we prepared some games. Among them, there is a game like this: First, let the children surrounded by a large circle. He then randomly assigned a number m, so that number of children 0 gettin number. Cried every time m-1 the children sing a song to be out of the line, then any of the gift box in choosing a gift, and not return to the circle, starting with his next child, continue 0 ... m-1 countin ... go on ... until the last remaining child, you can not perform, and get the cattle off the rare "Detective Conan" Collector's Edition (limited places oh! _ ). You want to try next, which the children will get the gifts it? (NOTE: The number of children is from 0 to n-1)
if no children, return -1

solve:

thought:

If just the last number off the winner, then we can solve the problem by mathematical induction, the sake of discussion, first issue slight changes do not affect the original intent:

Problem description: n individual (numbers 0 ~ (n-1)), from 0 Countin, report (m-1) exit, the remaining people continue to count off from zero. Seeking winner number.

We know that the first person (number must be m% n-1) After dequeue, the remaining n-1 to form a new individual Josephus (in number of k = m% n began)

k k + 1 k + 2 ... n-2, n-1, 0, 1, 2, ... k-2 and k starts from 0 packets.

We just need to start every time i in this position, re-find the first m-1 elements can be.

python code:

# -*- coding:utf-8 -*-
from collections import deque
class Solution:
    def LastRemaining_Solution(self, n, m):
        # write code here
        if not n:
            return -1
        res=range(n)
        i=0
        while len(res)>1:
            i=(i+m-1)%len(res)   #从i开始第m-1元素
            res.pop(i)
        return res.pop()
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/105064563