Title Description
Every year children's Day, Nowcoder will prepare some small gifts to visit the orphanage children, this year is also the case. HF as the senior veteran of the Nowcoder, naturally also prepared some small games. Among them, there is a game like this: first, let the children surround a big circle. Then, he randomly assigned a number m, so that the number of children numbered 0 began to count. Every time the child shouted to M to sing a song, and then can be in the Gift box arbitrary selection of gifts, and no longer back to the circle, from his next child, continue to 0...m-1 count off .... Go on like this .... Until the last child left, can not perform, and get Nowcoder valuable "Detective Conan" Collector's Edition (limited number of seats Oh!!) ^_^). Please try to think, which one of the children will get the present?
Thinking Analysis:
1. Define an array to store the children's numbers, starting from 0;
2. Define two variables, I means array subscript (number), J indicates the number to be reported now;
3. Find the person who will be out of the circle and then reduce the number of people in the circle by 1, and then put the number corresponding to the value of the array in the ArrayList after the value of 1, and finally will be counted J 1;
4. When a vacancy is encountered, jump to the next position, but J does not add one, that is, the position is not counted.
Code:
<span Style= "FONT-SIZE:18PX;" >import java.util.*;p Ublic class Solution {public int lastremaining_solution (int n, int m) {if (n<=0) { return-1; } int []arrays=new int[n]; ArrayList list=new ArrayList (); for (int i=0;i<n;i++) {arrays[i]=i; } int len=n; int i=0; int j=1; while (len>0) {if (arrays[i%n]>=0) {if (j%m==0) {////Find the person to be circled and reduce the number of people in the circle by a list . Add (arrays[i%n]); Arrays[i%n]=-1; i++; len--; J=1; }else{i++; j + +; }}else{i++;////encountered a vacancy, jumped to the next, but J not add one, that is, this position has no count}} int num= (int) list. Get (n-1); return num; }}</span>
The game of the Children of the Offer (31) (the last remaining number in the circle)