约瑟夫问题

有n个人围成一圈,顺序编号。从第一个人开始报数,凡报到m的人退出圈子,问最后一个圈中的人的编号。

import java.util.LinkedList;

/**
* author Akalius Kung 2008-2-10
**/
public class Josephus {

private static int removeNM(int n, int m) {  
  LinkedList<Integer> list = new LinkedList<Integer>();  
  for(int i = 0; i < n; i++){
  list.add(new Integer(i));  
  }
  int removed = 0; 
  while(list.size() > 1) {  
  removed = (removed + m - 1) % list.size();  
      list.remove(removed);  
  }  
  return list.get(0).intValue();  
}

public static void main(String[] args) throws Exception {  
  System.out.println(removeNM(3,1));  
    } 
 
}  

最简单原始的算法,用数组记录谁被out了。  
  int removed = 0;  // location which will be removed
  int leftLen=list.size(); // num of which value is not -1
  while(leftLen > 1) { // if still have elem not removed
for(int i=0;i<list.size();i++){
if(a[i]==-1){ // if elem has been removed, skip it
removed ++;
}
if(i==(removed + m - 1)% list.size){ // finding the elem to be removed
a[i]=-1;
removed =i;
leftLen--;
}
}      

  }  
  return a[0];

你可能感兴趣的:(算法)