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
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:
当时,直观的就想分奇数/偶数,再递归。
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是为了以空间换时间,这里肯定不行的了
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
当时,直观的就想分奇数/偶数,再递归。
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是为了以空间换时间,这里肯定不行的了
相关文章推荐
- git 相关
- C++ map 插入 困惑
- 解决“指定的服务已经标记为删除”问题
- Java mysql jsp 时间对象的显示与处理
- jQuery选择器总结
- logstash date插件介绍
- Android系统应用开发(七)屏蔽Home键和屏幕的唤醒和休眠,AlarmManager
- 19. Remove Nth Node From End of List
- $("input[name=choose]").attr("checked", true);只执行一次,再次点击没有作用
- json解析
- jquery查找节点常用方法
- [Android测试] Android Studio+Appium+Java+Windows 自动化测试之二:Appium环境安装搭建
- Java形参是传值还是传引用
- 【转】实模式和保护模式
- logstash date插件介绍
- yii2-basic后台管理功能开发之三:自定义GridView列显示
- TLS
- java web每天定时任务
- 双系统重新安装完win10之后ubuntu启动项不见了
- CentOS 6.5/6.6 安装mysql 5.7 最完整版教程