您的位置:首页 > 其它

LeetCode 397. Integer Replacement

2016-09-13 10:06 190 查看
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


当时,直观的就想分奇数/偶数,再递归。

int integerReplacement(int n) {
if(n==1)
return 0;
if(n==INT_MAX)
return 32;
int r,rr;

int k=n&1;//取整数的最后一位
if(!k)
r=integerReplacement(n>>1)+1;//如果是偶数,递归,左移一位,加一
else//如果是奇数,无论加一还是减一,递归时都有两步操作,故加2.
{
r=integerReplacement(n>>1)+2;//左移时,末尾直接忽略
rr=integerReplacement((n+1)>>1)+2;//如果没考虑n=INT_MAX的情况,提交会报错,n+1溢出了
r=min(r,rr);
}
return r;
}

其实,刚开始时,想过用动态规划,代码是这样的:

</pre><div><pre name="code" class="cpp">int integerReplacement(int n) {
if(n==1)
return 0;
if(n==INT_MAX)
return 32;
vector<int> r(n+1);
for(int i=1;i<=n;i++)
{
int k=i&1;
if(!k)
r[i]=r[i<<1]+1;
else
{
r[i]=min(r[i<<1],r[(i+1)<<1])+2;
}
}
return r
;
}但这时会出现MLE,(Memory 超了),平时都是TLE(时间复杂度太高),当时还纳闷呢。现在想想,要是n=INT_MAX, 分配这么大的vector<int> 肯定会超的,一般采用DP是为了以空间换时间,这里肯定不行的了


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: