-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_397.java
36 lines (34 loc) · 962 Bytes
/
_397.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
30
31
32
33
34
35
36
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.function.LongConsumer;
/**
* LeetCode 397 - Integer Replacement
* <p>
* BFS to find the shortest path
*/
public class _397 {
public int integerReplacement(int n) {
Map<Long, Integer> dist = new HashMap<>();
Queue<Long> queue = new ArrayDeque<>();
queue.add((long) n);
dist.put((long) n, 0);
while (!queue.isEmpty()) {
long x = queue.poll();
if (x == 1) return dist.get(x);
LongConsumer push = num -> {
if (!dist.containsKey(num)) {
queue.add(num);
dist.put(num, dist.get(x) + 1);
}
};
if (x % 2 == 0) push.accept(x / 2);
else {
push.accept(x + 1);
push.accept(x - 1);
}
}
return -1;
}
}