您的位置:首页 > 其它

LeetCode 397 Integer Replacement

2016-09-17 23:13 337 查看
iven a positive integer n and you can do operations as follow:

If n is even, replace n with 
n/2
.
If n is odd, you can replace n with either 
n +
1
 or 
n - 1
.

What is the minimum number of replacements needed for n to become 1?

Example 1:
Input:
8

Output:
3

Explanation:
8 -> 4 -> 2 -> 1


Example 2:
Input:
7

Output:
4

Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1


xxxxxxxxxx0 -> n = n / 2
0000000011 -> n = n - 1
xxxx1xxxx11 -> n = n + 1
xxxxxxxxx01 -> n = n - 1

为什么会xxxx1xxxx11 --> n = n + 1呢?

反证:如果xxxx1xxxx11 -> n = n -1那么n->xxxx1xxxx10,n>>1后,立即又变成了xxxx1xxxxx1,这时候又要进行加减运算,这样会使得中间过程更多,而如果此时 n=n+1,则会变成 xxxx1xxxx00,可以连续进行至少两次>>1的运算。结果肯定比n=n-1的好。

xxxxxxxxx01 -> n = n - 1,同样,如果n=n+1就变成了xxxx1xxxx10,n>>1后,立即又变成了xxxx1xxxxx1,所以不好,此时n=n-1的话,xxxxxxxxx01就变成了 xxxx1xxxx00
,可以连续进行至少两次>>1的运算。中间过程更加简练。

Runtime:
4 ms

public int integerReplacement(int n) {
if (n == 1) return 0;
if (n == 3) return 2;
if (n == Integer.MAX_VALUE) return 32;
if (n % 2 == 0) return integerReplacement(n / 2) + 1;
return (n& 3) == 3?integerReplacement(n +1) + 1:integerReplacement(n - 1) + 1;
}

不考虑更快的话,这种思路更简单。Runtime: 7 ms

public int integerReplacement(int n) {
if (n == 1) return 0;
if (n == Integer.MAX_VALUE) return 32;
if (n % 2 == 0) return integerReplacement(n / 2) + 1;
return Math.min(integerReplacement(n - 1), integerReplacement(n + 1)) + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode