問題描述: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