File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
problems/397. Integer Replacement Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1
1
# 397. Integer Replacement
2
2
3
+ ## #1 BFS[ AC]
4
+
5
+ ### 思路
6
+
7
+ 把每个数字看做图中的一个节点,两个节点之间是否有边相连,通过` n %2 == 0 -> n/2 ` 和` n % 2 != 0-> n+1, n-1 ` 这个条件来判断,这样就把问题看做是一个图。最后,通过广度优先遍历找到最近的路径。
8
+
9
+ ![ Screen Shot 2018-04-13 at 11.05.31] (../../../../../../../Desktop/Screen Shot 2018-04-13 at 11.05.31.png)
10
+
11
+ ### 算法
12
+
3
13
``` java
4
14
class Solution {
5
15
public int integerReplacement (int n ) {
@@ -28,3 +38,33 @@ class Solution {
28
38
}
29
39
```
30
40
41
+ 上面例子的执行方式如下所示:
42
+
43
+ ![ Screen Shot 2018-04-13 at 11.07.08] (../../../../../../../Desktop/Screen Shot 2018-04-13 at 11.07.08.png)
44
+
45
+ ### 复杂度分析:
46
+
47
+ - ?
48
+ - 空间复杂度:$O(logn)$
49
+
50
+ ## #2 位操作[ AC]
51
+
52
+ ### 算法
53
+
54
+ ``` java
55
+ public int integerReplacement(int n) {
56
+ int c = 0 ;
57
+ while (n != 1 ) {
58
+ if ((n & 1 ) == 0 ) {
59
+ n >>> = 1 ;
60
+ } else if (n == 3 || Integer . bitCount(n + 1 ) > Integer . bitCount(n - 1 )) {
61
+ -- n;
62
+ } else {
63
+ ++ n;
64
+ }
65
+ ++ c;
66
+ }
67
+ return c;
68
+ }
69
+ ```
70
+
You can’t perform that action at this time.
0 commit comments