【剑指offer】孩子们的游戏(圆圈中最后剩下的数)

本文介绍了一种在儿童节游戏中确定最后获胜者的方法,通过循环链表和列表两种方式实现,旨在找出编号为0到n-1的小朋友中,谁将获得最终的“名侦探柯南”典藏版礼物。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)

如果没有小朋友,请返回-1

题解一

public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        if(n == 0)
            return -1;
        Chain chain = new Chain();
        for(int i=0;i<n;i++) {
            //chain.add(new Child(chain.count++));这样写的话会导致线程安全性问题
            chain.add(new Child(i));
        }
        Child luckyChild = chain.start;
        int i=-1;
        while(chain.count>1) {
            i++;
            if(i == m-1) {
                chain.delete(luckyChild);
                i=-1;
            }
            luckyChild = luckyChild.right;
        }
        return chain.start.id;
    }
    private class Child {
        int id;
        Child left;
        Child right;
        public Child(int id) {
            this.id = id;
        }
    }

    private class Chain {
        int count = 0;
        Child start;
        Child end;

        public void add(Child c) {
            if(count == 0) {
                start = c;
                end = c;
            } else {
                end.right = c;
                start.left = c;
                c.left = end;
                c.right = start;
                end = c;
            }
            count++;
        }

        public void delete(Child c) {
            if(count == 0)
                return;
            else if(count == 1) {
                start = null;
                end = null;
            } else {
                c.left.right = c.right;
                c.right.left = c.left;
            }
            if(c == start)
                start = c.right;
            if(c == end)
                end = c.left;
            count--;
        }
    }
}

题解二

import java.util.*;

public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        if(n < 1 || m < 1)
            return -1;
        List<Integer> list = new LinkedList<Integer>();
        for(int i=0;i<n;i++) {
            list.add(i);
        }
        int cur = -1;
        while(list.size() > 1) {
            for(int i=0;i<m;i++) {
                cur++;
                if(cur == list.size())
                    cur = 0;
            }
            list.remove(cur);
            cur--;
        }
        return list.get(0);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值