【劍指offer】62、圓圈中最後剩下的數字
阿新 • • 發佈:2018-07-23
== str rem 過程 開始 continue 最後一個元素 last main
題目
0~n-1這n個數字排成一個圓圈,從0開始,每次刪除第m個數字,求出圓圈裏剩下的最後一個數字
思路
直接用數組模擬圓圈,模擬刪除的過程
class Solution { public: int LastRemaining_Solution(int n, int m) { if(n<1||m<1) return -1; int[] array = new int[n]; int i = -1, step = 0, count = n; while(count > 0){ //跳出循環時將最後一個元素也設置為了-1i++; //指向上一個被刪除對象的下一個元素。 if(i >= n) i = 0; //模擬環。 if(array[i] == -1) continue; //跳過被刪除的對象。 step++; //記錄已走過的。 if(step == m) { //找到待刪除的對象。 array[i] = -1; step= 0; count--; } } return i;//返回跳出循環時的i,即最後一個被設置為-1的元素 } };
【劍指offer】62、圓圈中最後剩下的數字