forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_390.java
29 lines (27 loc) · 939 Bytes
/
_390.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.fishercoder.solutions;
public class _390 {
public static class Solution1 {
/**
* credit: https://discuss.leetcode.com/topic/55870/share-my-solutions-for-contest-2 instead of
* literally removing half of the elements in each scan, this solution is just moving the
* pointer to point to next start position So brilliant!
*/
public int lastRemaining(int n) {
int remaining = n;
int start = 1;
int step = 2;
boolean forward = true;
while (remaining > 1) {
remaining /= 2;
if (forward) {
start = start + step * remaining - step / 2;
} else {
start = start - step * remaining + step / 2;
}
step *= 2;
forward = !forward;
}
return start;
}
}
}