package ttt; import java.util.HashMap; import java.util.Map.Entry; /** * 有17個人圍成一圈(編號0~16),從第0號的人開始從1報數,凡報到3的倍數的人離開圈子,然后再數下去, * 直到最后只剩下一個人為止,問此人原來的位置是多少號? * */ public class n人報數m時離開 { public static void main(String[] args) { HashMap<Integer, Integer> theQuee = new HashMap<Integer,Integer>(); for (int i = 0; i < 17; i++) { theQuee.put(i, i+1);//編號,固定位置 } HashMap<Integer, Integer> itretMap = itretMap(theQuee,theQuee.size()); for (Entry<Integer,Integer> entry : itretMap.entrySet()) { if(entry.getValue()!= 0){ System.out.println("結果:"+entry.getKey()); } } } //遍歷Map並給非3的倍數的Key的value+1 public static HashMap<Integer, Integer> itretMap(HashMap<Integer,Integer> map,int lenth){ int sum = 0; for (Entry<Integer,Integer> entry : map.entrySet()) { int value = entry.getValue(); if(value%3 != 0){//不可以整除 entry.setValue(value+lenth);//加 sum++;//進入下一輪 }else{ if(0!=entry.getValue()){//避免重復淘汰 entry.setValue(0);//淘汰 lenth --;//參與者-1 } } } if(sum>1){// System.out.println("還要繼續,還有:"+sum); return itretMap(map,sum); }else{//已決出勝出者 return map;//返回map } } }
加班回來的路上看到一個這樣的題,題目就是標題,
(原題地址:http://www.cnblogs.com/tonybinlj/archive/2009/01/04/1367856.html),然后自我感覺用了個比較拙劣的方式,最后還是實現了。這里的17和3當然可以當做參數m,n來處理。。
弄完網上找了找。C系列實現形式思路基本上是一樣的。
然后數學好的三行代碼就搞定了。。遍歷次數也是最少的。效率達到O(n):
public static void main(String[] args) { int n =0; for (int i = 2; i <= 17; i++) { n = (n+3)%i; } System.out.println(n); }