真的模拟去删超时了。看了题解才写出来的,log(n)的复杂度,确实很强,不需要真的删,记录等差数列的首项就可以。
class Solution {
public:
int lastRemaining(int n) {
int a0=1, cnt=n, step=1;
bool left=true; // 是否从左开始
while(cnt>1){
if (left==true){
// 从左到右
a0 = a0 + step;
left = false;
}
else if (left==false){ // 从右到左
if (cnt%2==1){
a0 = a0+step;
}
left = true;
}
step = step <<1;
cnt = cnt >>1;
}
return a0;
}
};