50个人围成一圈数到3和3的倍数时出圈,问剩下的人是谁?

37 篇文章 0 订阅


1下面三种实现方式,可见使用数组的方式性能最优!

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    int size = 9999;
    int[] queue = new int[size];

    for (int i = 0; i < size; i++) {
        queue[i] = i + 1;
    }

    int meilunjishu;
    int count = 0;
    int lun = 0;
    do {

        meilunjishu = 0;
        //          System.out.println("第"+ (++lun)+"轮:");
        for (int index = 0; index < queue.length; index++) {
            if (queue[index] == -1)
                continue;
            count = count + 1;
            meilunjishu++;//本轮计数
            if (count % 3 == 0) {
                //                 System.out.print(" 排除"+queue[index]);
                queue[index] = -1;
            }
        }
        //         System.out.println();

    } while (meilunjishu > 1);
    for (int zhi : queue) {
        if (zhi == -1) ;
        else
            System.out.println("最后剩余" + zhi);
    }
    System.out.println(System.currentTimeMillis() - start);


    long start2 = System.currentTimeMillis();
    LinkedList l = Lists.newLinkedList();
    for (int b = 0; b < size; b++) {
        l.add(b + 1);
    }
    int lcount = 0;
    while (l.size() > 1) {
        Iterator iterator = l.iterator();
        while (iterator.hasNext()) {
            iterator.next();
            lcount++;
            if (lcount % 3 == 0) {
                iterator.remove();
            }
        }
    }
    System.out.println(l);
    System.out.println(System.currentTimeMillis() - start2);
    long start3 = System.currentTimeMillis();
    System.out.println(cycle(size,3));
    System.out.println(System.currentTimeMillis() - start3);
}

public static int cycle(int total, int k) {  //功能方法
    List<Integer> dataList = new LinkedList<Integer>();//创建链表对象
    for (int i = 0; i < total; i++)  //添加数据元素
        dataList.add(new Integer(i + 1));
    int index = -1;  //定义下标,模拟已经去掉一个元素,因此从-1开始
    while (dataList.size() > 1) { //一直循环去除数据,直到只剩下一个元素
        index = (index + k) % dataList.size();//得到应该出局的下标
        dataList.remove(index--);  //去除元素
    }
    return ((Integer) dataList.get(0)).intValue();//返回它的值
}
 
结果:
最后剩余2689
7
[2689]
32
2689
100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自驱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值