博客
关于我
圆桌报数问题(剑指offer-62)
阅读量:348 次
发布时间:2019-03-04

本文共 1171 字,大约阅读时间需要 3 分钟。

1、题目描述

    一圈共有N个人,开始报数,报到M的人自杀,然后重新开始报数,问最后自杀的人是谁?

                                 

如图:内环表示人排列的环,外环表示自杀顺序;上面N=41,M=3。

2、解题思路一:时间复杂度O(MN):

     使用一个大小为N的bool数组来保存每个人是否被杀,然后一直循环遍历这个数组,直到所有人都被杀死。在遍历过程中需要设置两个变量iji变量表示报数的大小,j变量则是一个索引,当索引为j的人如果没有被杀死,则i加一,若i的报数刚好等于M,则把索引为j的人杀死,详细代码如下:

void CircleTable(int nums, int kill) {        //nums表示人数,kill表示报该数时被杀死	map
live; for (int i = 0; i <= nums; i++) //初始化数组,所有人为活着的 live[i] = true; int count = 0; int i = 0; int output; for (int j = 1;; j++) { //循环遍历这个数组 if (live[j%nums] == 1) { //索引为j的人活着,则报数 i++; if (i%kill == 0) { //如果报数等于kill,则被杀死 live[j%nums] = false; output = j%nums; cout << "i:" << i << ",j:" << j << ",last:" << output << endl; count++; if (count == nums) break; } } } }

3、解题思路二:时间复杂度O(MN)

    使用一个队列来保存圆桌的每个人。接着,依次把从队头开始,把前kill - 1个人出队并给push到队列尾部,然后把队头的第一个元素pop,完成一个人的自杀。一直循环,直到队列只有一个人为止,则这个人为最后自杀的那个。代码如下:

void CircleTable(int nums, int kill) {	queue
live; for (int i = 0; i < nums; i++) live.push(i + 1); while (live.size()!=1) { for (int j = 0; j < kill - 1; j++) { live.push(live.front()); live.pop(); } live.pop(); } cout <<"last:"<
<

 

转载地址:http://ayqe.baihongyu.com/

你可能感兴趣的文章
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>