您的位置:首页 > 其它

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

2017-11-19 11:20 337 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐