Article Directory
Problem Description
The n numbers 0,1, n-1 are arranged in a circle, starting with the number 0, and deleting the mth number from this circle each time. Find the last number left in this circle.
For example, the 5 digits 0, 1, 2, 3, and 4 form a circle, and the third digit is deleted every time from the digit 0, then the first 4 digits deleted are 2, 0, 4, 1, and so on. The remaining number is 3.
Input: n = 5, m = 3
Output: 3
Problem solving report
- The number of n person is , delete the number as person, the next person deleted from starts counting, the corresponding number sequence is 。
- Remaining Make a mapping of the number of person, and map it into , then in the new sequence is the original sequence 。
- in other words, person last remaining number is , then corresponding The number of the last remaining person of people is 。
- make means number of the last person left, then 。
Implementation code
- Recursive
class Solution {
public:
int f(int n, int m) {
if (n == 1)
return 0;
int x = f(n - 1, m);
return (m + x) % n;
}
int lastRemaining(int n, int m) {
return f(n, m);
}
};
- Iterate
class Solution {
public:
int lastRemaining(int n, int m) {
int ans=0;
for(int i=2;i<=n;i++){
ans=(ans+m)%i;
}
return ans;
}
};