public static int getLastPeopleNum(ArrayList<Bean> tempList, int mode) {
if (tempList != null) {
ArrayList<Bean> list = (ArrayList<Bean>) tempList.clone();
if (list.size() > 1 && list.size() > mode - 1) {
for (int i = 0; i < mode; i++) {
if (i == mode - 1) {
Bean bean = list.remove(i);
}
}
tempList = getNewList(list, mode - 1);
return getLastPeopleNum(tempList, mode);
} else if (list.size() == 1) {
return list.get(0).num;
} else {
int index = (mode - 1) % list.size();
Bean bean =list.remove(index);
return getLastPeopleNum(list, mode);
}
}
return -1;
}
public static ArrayList<Bean> getNewList(ArrayList<Bean> tempList, int position) {
if (tempList != null && tempList.size() > 1) {
ArrayList<Bean> afterList = new ArrayList<>();
ArrayList<Bean> beforeList = new ArrayList<>();
int size = tempList.size();
for (int i = 0; i < position; i++) {
beforeList.add(tempList.get(i));
}
for (int i = position; i < size; i++) {
afterList.add(tempList.get(i));
}
afterList.addAll(beforeList);
return afterList;
}
return tempList;
}
public static class Bean {
int num;
}
public static void main(String[] args) {
//标号1-n的n个人首尾相接,1到3报数,报到3的退出,求最后一个人的标号
ArrayList<Bean> list = new ArrayList<Bean>();
for (int i = 1; i < 8; i++) {
Bean object = new Bean();
object.num = i;
list.add(object);
}
int result = getLastPeopleNum(list, 4);
System.out.println("result=" + result);
}
思路:输到某个数字的人直接退出数组,然后翻转数据即可,数到多少号的数值只是一种模式,作为参数丢进去,如果号码的参数大于数组的大小,这时候直接取余移除直至最后一个。