剑指OFFER
题目描述:0,1,…, n-1这n个数字围成一圈,从0开始报数,每次从圈中删除第m个数字。求圈中最后剩下的数字。
struct ListNode{
int val;
ListNode* next;
ListNode(): val(-1), next(nullptr){}
ListNode(int x): val(x), next(nullptr){}
};
// math method
int joesphus(int n, int m){
if(n < 1 || m < 1){
return -1;
}
int ans = 0;
for(int i = 2; i <= n; i++){
ans = (ans + m) % i;
}
return ans;
}
// recurisive
int joesphusII(int n, int m){
if(n < 1 || m < 1){
return -1;
}
if(n == 1){
return 0;
}
return (joesphusII(n - 1, m) + m) % n;
}
// recurent list
int joesphusIII(int n, int m){
if(n < 1 || m < 1){
return -1;
}
ListNode* head = new ListNode(0);
ListNode* pre = head;
for(int i = 1; i < n; i++){
ListNode* tmp = new ListNode(i);
pre -> next = tmp;
pre = tmp;
}
pre -> next = head;
while(n != 1){
for(int i = 1; i < m - 1; i++){
head = head -> next;
}
head -> next = head -> next -> next;
head = head -> next;
n--;
}
return head -> val;
}