描述
Given a positive integer n and you can do operations as follow:
1.If n
is even, replace n
with n/2
.
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
题目意思很简单,不说了。
因为这个题目放在了【数学】这个类别下,我一直在推导是否有什么公式可以一步到位O(1)的解决。最后推了一会儿放弃了,感觉看不出来有什么规律。
因为题目当中有除以2其实一直直接暴力搜索的话,时间复杂度大概也就是O(logN)
最早我就简单的暴力搜索答案,后面发现搜索过程中可能会遇到重复搜索的
举个例子,题目样例搜索7的答案,如果7的最少变换次数是4,那么可以知道14肯定是7的基础上+1,所以可以开辟一个map把计算结果保存起来,一旦遇到曾经搜索过的点,就直接返回当前的答案。这样可以越搜越快。这就有点带DP的思想了
不做优化的话是50ms,做了优化是9ms
class Solution{
public:
map<int,int> dp;
Solution()
{
dp.clear();
}
int get_min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
int integerReplacement(int n)
{
if(n==1)
return 0;
else
{
if(dp[n]>0)
return dp[n];
else
{
if(n%2==0)
{
dp[n]=integerReplacement(n/2)+1;
return dp[n];
}
else
{
dp[n]=get_min(integerReplacement(n-1)+1,integerReplacement(n+1)+1);
return dp[n];
}
}
}
}
};