8000 update 397 · zykjcom/leetcode@0074d81 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0074d81

Browse files
committed
update 397
1 parent 27214f3 commit 0074d81

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

problems/397. Integer Replacement/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# 397. Integer Replacement
22

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+
313
```java
414
class Solution {
515
public int integerReplacement(int n) {
@@ -28,3 +38,33 @@ class Solution {
2838
}
2939
```
3040

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+

0 commit comments

Comments
 (0)
0