题目描述
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
如果没有小朋友,请返回-1
解题思路:
使用数组模拟循环链表,用startIndex作为指向数组的下标位置。
不断循环m次删去节点,直至链表中只剩一个节点为止。
代码实现:
class Solution {
/*
使用数组模拟循环链表,用startIndex作为指向数组的下标位置。
不断循环m次删去节点,直至链表中只剩一个节点为止。
*/
public:
int LastRemaining_Solution(int n, int m)
{
int* people = NULL;//小朋友
int ans = -1;//获得名贵礼品的小朋友编号
int j = 0;
if (people == NULL) {
people = new int[n];
for (int i = 0; i < n; i++) {
people[i] = i;//初始化编号
}
}
int startIndex = 0;
while (people[0] != -1 && n > 0) {
int removeIndex = (startIndex+m-1) % n;//需出列的编号的下标
ans = people[removeIndex];
startIndex = removeIndex;
while (removeIndex < n-1) {//删除出列的编号,后面的编号往前移动一位
people[removeIndex] = people[removeIndex+1];
removeIndex++;
}
people[n-1] = -1;
n--;
}
return ans;
}
};
效率:
解题思路2:
用ArrayList模拟整个过程得出结果
代码实现:
import java.util.ArrayList;
public class Solution {
/*
用ArrayList模拟整个过程得出结果
*/
public int LastRemaining_Solution(int n, int m) {
if (m == 0 || n == 0) {
return -1;
}
ArrayList<Integer> data = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
data.add(i);初始化编号
}
int index = 0;
while (data.size() > 1) {
index = (index + m-1) % data.size();需出列的编号的下标
data.remove(index);删除出列的编号,后面的编号自动往前移动一位
}
return data.get(0);
}
}