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
If n is odd, you can replace n with either
What is the minimum number of replacements needed for n to become 1?
Example 1:
Example 2:
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
不考虑更快的话,这种思路更简单。Runtime: 7 ms
If n is even, replace n with
n/2.
If n is odd, you can replace n with either
n + 1or
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 (397) Integer Replacement
- 397. Integer Replacement
- 397. Integer Replacement
- 397. Integer Replacement
- LeetCode Integer Replacement
- (LeetCode)Integer Replacement --- 整数替换
- LeetCode Integer Replacement
- 397. Integer Replacement
- 397. Integer Replacement
- Leetcode 397. Integer Replacement (Easy) (cpp)
- Math-397-Integer Replacement
- Leetcode Integer Replacement
- LeetCode-Integer Replacement
- Leetcode: Integer Replacement
- 397. Integer Replacement
- [LeetCode] Integer Replacement 整数替换
- 397. Integer Replacement
- 【leetcode】String to Integer (atoi)
- Leetcode 8. String to Integer (atoi)
- LeetCode(8)StringToInteger