淘宝面试题 n个人围成一圈,报到m的人出列
有N个人围成一圈,第一个人从1开始报数,报到M的人出列,求最后一个出列的人。 这是一个约瑟夫环问题,下面给出了java实现的例子:
package com.juziku;
import java.util.Arrays;
/**
* n个人围成一圈,报到m的人出列
* @author sunlightcs
* 2011-3-8
* http://hi.juziku.com/sunlightcs/
*/
public class Queue {
public static void main(String[] args) {
queue(10, 3);
}
/**
* 最后出队的人
* @param total 总的人数
* @param num 第几号出队
*/
public static void queue(int total, int num){
//定义一个数组,true表示没有出队列的,false表示已经出队列的
boolean []arr = new boolean[total];
Arrays.fill(arr, true);
//移动变量,如:1 2 3 1 2 3 1 2
int next = 1;
//数组下标
int index = 0;
//剩下的人数
int count = total;
//如果剩下的人数为1人时,停止报数
while(count>1){
if(arr[index] == true){
if(next == 3){
arr[index] = false;
//剩下的人数减1
--count;
//移动变量复位,从1开始报数
next = 1;
System.out.println("依次出列的人为:"+(index+1));
}else{
++next;
}
}
++index;
if(index == total){
//数组下标复位,从0开始新重遍历
index = 0;
}
}
for(int i=0; i<total; i++){
if(arr[i] == true){
System.out.println("最后出列的人为:"+(i+1));
}
}
}
}
全文请访问:人人编程
args :wink:
代码行数太多,逻辑太啰嗦,递归就简单多了。
这个之前自己写的,虽然不完全一样,但都差不多 public class MyCount3Quit{ public static void main(String agrs){ KidCircle kid =new KidCircle(500); int n=kid.count(0,2); kid.delNext(n); while(kid.getLen()>1){ n=kid.count(n,3); kid.delNext(n); } System.out.println(n); } }
class KidCircle{ // private int kid; private int next; private int len; KidCircle(int i){ len=i; // kid=new int*; next=new int*; for(int j=0;j<i-1;j++){ //kid=j; next=j+1; } next=0; }
public int getLen(){return len;}
public int length(){ return len; }
public int count(int n, int i){ //返回第I个人的位置 for(int j=1;j<i;j++){ n=next; } return n; }
public void delNext(int i){ next*=next]; len--; } }
是这个意思了。
哈哈,又见数据结构了 关于题目,有点不明:报到M,意思是说M出列后又从1开始报?
习惯问题, :D
有一个小小的疑问:为什么不直接用 if(arr),而非要用if(arr == true)呢?
见:http://baike.baidu.com/view/717633.htm#sub717633
n个人最后剩下来的人序号为f(n,m),死了一个人后其实序号是不变的,以此建立递推关系 死了一人后算f(n-1,m)得到的序号其实是从第m个开始计数的,所以要加m
#include "stdafx.h" #include"iostream" #define Size 100
typedef int type ; using namespace std;
void kill(int a,int len,int n) { int b; int j=1; for(int i=n;i<len;i++) { b=a; j++; } for(int i=1;i<n;i++) { b=a*; j++; } for(int i=1;i<len;i++) { a*=b*; } }
int _tmain(int argc, _TCHAR* argv) { int a,b,m,n,len; cout<<"请输入多少人:"; cin>>len; cout<<"请输入从几开始报数"; cin>>m; cout<<"请输入数到几的人处死"; cin>>n; int t=m; int tn=1;
}
纯数组
还是不明白这个递推公式 是怎么求出来的?
int r = 0;
for (int i = 2; i <= n; i++) {
r = (r + m) % i;
}
return r + 1;
居然可以有这么强悍的实现。。。 没看懂 能讲一下不。。
int current = -1; List nl = new ArrayList(); for(int i = 1;i<=n;i++){ nl.add(i); }
集合比数组更方便一些(size()方法),我承认,我比前面那位数组实现的同学更懒 -0-
单向循环链表啊,数据结构最基础的问题了
不知道你这个是怎么测的,难道结果不是1吗
关于前面的代码, 我测试了下发现并不是所有的情况都对的,比如n=2, m=2的情况
:x :x
数组的方法, 闲着没事也试试
if(next == num){
arr = false;
吧。。。