class Solution {
Map<Long, Integer> map = new HashMap();
public int integerReplacement(int n) {
return minCount((long) n);
}
public int minCount(long n) {
if(n == 1) return 0;
if(map.containsKey(n)) {
return map.get(n);
}
int res = 0;
if(n % 2 == 0) {
res = 1 + minCount (n / 2);
} else {
res = 1 + Math.min(minCount(n + 1), minCount(n -1));
}
map.put(n, res);
return res;
}
}
341. Flatten Nested List Iterator
public class NestedIterator implements Iterator<Integer> {
Deque<NestedInteger> stack = new ArrayDeque();
public NestedIterator(List<NestedInteger> nestedList) {
prepareStack(nestedList);
}
@Override
public Integer next() {
if(!hasNext()) {
return null;
}
return stack.pop().getInteger();
}
@Override
public boolean hasNext() {
while(!stack.isEmpty() && !stack.peek().isInteger()) {
List<NestedInteger> list = stack.pop().getList();
prepareStack(list);
}
return !stack.isEmpty();
}
private void prepareStack(List<NestedInteger> nest) {
for(int i = nest.size() - 1; i >= 0; i--) {
stack.push(nest.get(i));
}
}
}
509. Fibonacci Number
class Solution {
public int fib(int n) {
if(n <= 1) {
return n;
}
int pre = 0;
int prev = 1;
int cur = 0;
for(int i = 2; i <= n; i++) {
cur = pre + prev;
pre = prev;
prev = cur;
}
return cur;
}
}