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

Topic description
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 calls 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, and continuing 0...m -1 count.... 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)

My approach is to use an ArrayList to store the numbers, and then delete one at a time until there is one left. The hardest part is figuring out which next element should be removed.

import java.util.ArrayList;
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        if(n<=0||m<=0)return -1;
		int count = 0;//The subscript of the element to be deleted that changes with the change of p
		ArrayList<Integer> p = new ArrayList<Integer>();//The rest of the people
		for (int i = 0; i < n; i++) {
			p.add(i);//Number
		}
		
		while(p.size()>1) {
			count+=m-1;
			while(count>p.size()-1) {//Continue to loop until a subscript that meets the conditions is found
				count = count - p.size();//Because count starts from 0, it needs to be subtracted by one more, count-(p.size()-1)-1
			}
			p.remove(count);
			if(count ==p.size())count =0;//After the last element is deleted, its next one is 0, why is not p.size()-1 here, because the previous step is deleted
			//An element is added, so the original subscript is to add one to the current last subscript
		}
		
		return p.get(0);
    }
}

d Some people have found a pattern, that is, the number of the next person is m%n, which is awesome

public class Solution
{
    public int LastRemaining_Solution(int n, int m)
    {
        if(n==0||m==0)return -1;
        int s=0;
        for(int i=2;i<=n;i++)
        {
            s=(s+m)%i;
        }   
       return s ;
    }
}


Guess you like

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