面試題62:圓圈中最后剩下的數字
題目要求:
0,1,2...n-1這n個數字拍成一個圓圈,從數字0開始,每次從這個圓圈里刪除第m個數字,求剩下的最后一個數字。例如0,1,2,3,4這5個數字組成的圈,每次刪除第3個數字,一次刪除2,0,4,1,因此最后剩下的是3。
解題思路:
最直接的思路是用環形鏈表模擬圓圈,通過模擬刪除過程,可以得到最后剩下的數字,那么這道題目就變成了刪除鏈表中某一個節點。假設總節點數為n,刪除一個節點需要走m步,那么這種思路的時間復雜度為o(mn),空間復雜度o(n)。
思路2比較高級,較難理解,可遇不可求。將圓圈表示成一個函數表達式,將刪除節點的過程表示成函數映射的變化,時間復雜度o(n),空間復雜度o(1)!有興趣的話可以搜素”約瑟夫環“去詳細了解。
package chapter6;
import structure.ListNode;
/**
* Created with IntelliJ IDEA
* Author: ryder
* Date : 2017/8/20
* Time : 16:20
* Description:圓圈中最后剩下的數字
* n=5,m=3,從0,1,2,3,4組成的圓中刪除第3個數字
* 依次刪除3,0,4,1,最終剩下的是3
**/
public class P300_LastNumberInCircle {
public static int lastRemaining(int n,int m){
if(n<1||m<1)
return -1;
ListNode<Integer> head = new ListNode<>(0);
ListNode<Integer> cur = head;
for(int i=1;i<n;i++){
ListNode<Integer> node = new ListNode<>(i);
cur.next = node;
cur = cur.next;
}
cur.next = head;
cur = head;
while (true){
//長度為1結束循環
if(cur.next==cur)
return cur.val;
//向后移動
for(int i=1;i<m;i++)
cur=cur.next;
//刪除當前節點
cur.val = cur.next.val;
cur.next = cur.next.next;
//刪除后,cur停在被刪節點的后一節點處
}
}
//另一個思路分析過程較復雜,不強求了。可搜約瑟夫環進行了解。
public static void main(String[] args){
System.out.println(lastRemaining(5,3)); //3
System.out.println(lastRemaining(6,7)); //4
System.out.println(lastRemaining(0,7)); //-1
}
}
運行結果
3
4
-1