难度: Medium
原题连接
内容描述
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
思路 1 - 时间复杂度: O(lgN)- 空间复杂度: O(1)******
无脑递归, beats 15.63%
class Solution:
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 0
if n % 2 == 0:
return 1 + self.integerReplacement(n // 2)
return 1 + min(self.integerReplacement(n - 1), self.integerReplacement(n + 1))
思路 2 - 时间复杂度: O(lgN)- 空间复杂度: O(1)******
烧脑数学证明
beats 59.38%
class Solution:
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
while n > 1:
res += 1
if n % 2 == 0:
n //= 2
elif n % 4 == 1 or n == 3:
n -= 1
else:
n += 1
return res
one explantion is intuitive (@shshwdr from wechat):
n = 2k + 1
n + 1 = 2k+2 (n+1) / 2 = k+1
n - 1 = 2k (n-1) / 2 = k
one of k and k+1 will be even, we want to get even number optimally at the end,
so we check which one is multiplier of 4 and choose it
but notice one edge case, n = 3, we would choose n - 1 = 2 instead of n + 1 = 4