问题描述:java
n个数字(下标为0, 1, …, n-1)造成一个圆圈,从数字0开始,每次从这个圆圈中删除第m个数字(当前数字从1开始计数)。当一个数字被删除后,从被删除数字的下一个数字开始计数,继续删除第m个数字。求这个圆圈中剩下的最后一个数字。node
分析:this
这是有名的约瑟夫环问题。spa
最直接的方法:code
使用链表来模拟整个删除过程。由于须要n个链表节点,因此空间复杂度为O(n)。每删除一个节点,都须要m次运算,因此时间复杂度为O(mn)。io
实现代码以下所示:ast
package oschina.IT100; import java.util.Scanner; /** * @project: oschina * @filename: IT18.java * @version: 0.10 * @author: JM Han * @date: 21:59 2015/12/19 * @comment: josephus * @result: */ public class IT18 { private static class Node{ public int no; public Node next; public Node(int no){ this.no = no; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the whole number: "); int total = sc.nextInt(); System.out.println("Enter the inter number: "); int count = sc.nextInt(); Node header = new Node(1); Node current = header; for (int i = 2; i <= total; i++){ current.next = new Node(i); current = current.next; } //cycle current.next = header; System.out.println("Below is the sequence of deletion: "); while(current.next != current){ for (int i = 1; i < count; i++){ current = current.next; } System.out.println("delete node: " + current.next.no); current.next = current.next.next; } System.out.println("The last node is: " + current.no); } }
代码输出:class
Enter the whole number: 10 Enter the inter number: 2 Below is the sequence of deletion: delete node: 2 delete node: 4 delete node: 6 delete node: 8 delete node: 10 delete node: 3 delete node: 7 delete node: 1 delete node: 9 The last node is: 5