[Swords offer] Children's games (the last remaining number in the circle)

topic

Children's game (last number left in the circle)

describe

Every year on Children's Day, Niu Ke will prepare some small gifts to visit the children in the orphanage, and this year is the same. As a senior veteran of Niu Ke, HF naturally prepared some small games. Among them, there is a game like this: First, let the children form a big circle. Then, he randomly assigned a number m, and let the children numbered 0 start counting. Every time the child who shouts m-1 will go out to sing a song, and then he can choose any gift from the gift box, and will not return to the circle, starting from his next child, continue 0...m-1 Report the number.... and so on.... until the last child left, you can not perform, and get the valuable "Detective Conan" collector's edition (limited places!! ^_^). Please try to think, which child will get this gift? (Note: Children are numbered from 0 to n-1)

ideas

  1. Can simulate ring operation
  2. There are mathematical ways to deduce the answer..

code

package com.wy.offer;

import java.util.LinkedList;

//孩子们的游戏(圆圈中最后剩下的数)  约瑟夫问题
public class T47 {

    public static void main(String[] args) {
        System.out.println(T47.LastRemaining_Solution(5,3));

    }

    public static int LastRemaining_Solution(int n, int m) {
        if(n<1||m<1){
            return -1;
        }
        // n 个小朋友,m表示out
        LinkedList<Integer> list = new LinkedList<>();
        for(int i=0;i<n;i++){
            list.add(i);
        }
        int index = -1;
        while (list.size()>1){
            index = (index + m) % list.size(); //模拟环
            list.remove(index);
            index--;
        }
        return list.get(0);
    }
    //数学的方法解题
    public static int LastRemaining_Solution2(int n, int m) {
        if(n<1||m<1){
            return -1;
        }
        int last = 0;
        for(int i=2;i<=n;i++){
            last = (last+m)%i;
        }
        return last;

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324818288&siteId=291194637
Recommended