397. Integer Replacement
problem
Given 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
Subscribe to see which companies asked this question
题目大意:
给定正整数n,你可以做如下操作:
如果n是偶数,将n替换为n/2
如果n是奇数,你可以将n替换为n + 1或者n - 1
求将n替换为1的最小次数
solution
难点在于判断是+1还是-1?
原则是尽量让最先几次中除法尽量多,尽量快速的变小,怎么判断???
- 递归解法
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 0
if n % 2:
return 1 + min(self.integerReplacement(n+1),self.integerReplacement(n-1))
else:
n /= 2
return 1 + self.integerReplacement(n)
discsss
https://discuss.leetcode.com/topic/59350/python-o-log-n-time-o-1-space-with-explanation-and-proof
分析出了什么时候+1 什么时候 -1,结论如下;具体为什么mark下之后分析
elif n % 4 == 1 or n == 3:
n -= 1
else:
n += 1
大致这么理解:
-
所有的偶数都是2n
-
所有的奇数都是2n+1
-
所以奇数 +1或者-1后 就变成了2(n+1)或者2n
-
奇数里面2n + 1 % 4 == 1 的表明n是偶数;2n + 1 %4 == 3 表明n是奇数
-
根据上面提到尽量多除的原则, 除,需要使的第二次的除法能进行(即能除4.) 那么此时如果n是奇数,那么我们应该选择+1变成2(n+1),反之是2n
-
(可以这么理解,为了能连续两次除2,要补成4的整倍数)

浙公网安备 33010602011771号