(算法题)标号1-n的n个人首尾相接,1到3报数,报到3的退出,求最后一个人的标号


    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);
    }

思路:输到某个数字的人直接退出数组,然后翻转数据即可,数到多少号的数值只是一种模式,作为参数丢进去,如果号码的参数大于数组的大小,这时候直接取余移除直至最后一个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值