the last remaining number 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 shouts to m-1 has 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 to count at 0...m-1.... and so on.... until the last child left, who 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)
- If there are no children, please return -1
Title link : last remaining number in the circle
code
/**
* 标题:圆圈中最后剩下的数
* 题目描述
* 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。
* 其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。
* 每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,
* 从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。
* 请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
* <p>
* 如果没有小朋友,请返回-1
* 题目链接:
* https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&&tqId=11199&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
*/
public class Jz46 {
/**
* 约瑟夫环,圆圈长度为 n 的解可以看成长度为 n-1 的解再加上报数的长度 m。因为是圆圈,所以最后需要对 n 取余。
*
* @param n
* @param m
* @return
*/
public int lastRemaining_Solution(int n, int m) {
if (n == 0) {
return -1;
}
if (n == 1) {
return 0;
}
return (lastRemaining_Solution(n - 1, m) + m) % n;
}
public static void main(String[] args) {
Jz46 jz46 = new Jz46();
System.out.println(jz46.lastRemaining_Solution(4, 6));
}
}
[Daily Message] Life is always full of unexpected warmth and endless hope. Always look ahead at all times, and you will be invincible when you are full of hope.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。