There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.
We keep repeating the steps again, alternating left to right and right to left, until a single number remains.
Find the last number that remains starting with a list of length n.
Solution
recursive, assume you know the answer of f(i) i < n, and you try to calculate the answer of f(n);
Code
class Solution {
public:
int f(int n,int dir) {
if (n == 1) return 1;
if (n % 2 == 0 && dir == -1) {
int ans = f(n / 2,-dir);
return ans + (ans - 1);
}
else if (n % 2 == 0 && dir == 1) {
int ans = f(n / 2,-dir);
int tmp = ans + ans;
return tmp;
}
else if (n % 2 == 1 && dir == 1) {
int ans = f(n / 2,-dir);
return ans + ans;
}
else if (n % 2 == 1 && dir == -1) {
int ans = f(n / 2,-dir);
return ans + ans;
}
return 0;
}
int lastRemaining(int n) {
return f(n,1);
}
};
没有评论:
发表评论