这题考察的是约瑟夫环,本人在面试中也有遇到,数学公式的方法请参照https://www.cnblogs.com/nxf-rabbit75/p/10707989.html
本人使用的是单向循环链表的方法,但是超时了,代码如下:
struct num{
int val;
struct num* next;
num():val(0), next(nullptr){}
};
class Solution {
public:
int lastRemaining(int n, int m) {
int i = 0;
struct num* head = new num();
head -> val = 0;
struct num* trans = head;
for(i = 1; i < n; i++){
struct num* temp = new num();
temp -> val = i;
trans -> next = temp;
trans = temp;
}
trans -> next = head;
trans = head;
int clock = 1;
while(trans -> next != trans){
if(clock != m){
trans = trans -> next;
clock++;
}else{
clock = 1;//注意下面删除操作的技巧,O(1)时间复杂度删除
head = trans -> next;
trans -> val = head -> val;
trans -> next = head -> next;
delete head;
}
}
return trans -> val;
}
};