当前位置:网站首页>算法---整数替换(Kotlin)
算法---整数替换(Kotlin)
2022-08-09 23:31:00 【小米科技Android 研发曹新雨】
题目
给定一个正整数 n ,你可以做如下操作:
如果 n 是偶数,则用 n / 2替换 n 。
如果 n 是奇数,则可以用 n + 1或n - 1替换 n 。
返回 n 变为 1 所需的 最小替换次数 。
示例 1:
输入:n = 8
输出:3
解释:8 -> 4 -> 2 -> 1
示例 2:
输入:n = 7
输出:4
解释:7 -> 8 -> 4 -> 2 -> 1
或 7 -> 6 -> 3 -> 2 -> 1
示例 3:
输入:n = 4
输出:2
提示:
1 <= n <= 231 - 1
解决思路
1.按照题目思路 直接递归求解
2.添加记忆化 防止重复运算
解决方法
方法1:
fun integerReplacementV2(n: Int): Int {
if (n == 1) return 0
return if (n % 2 != 0) {
2 + integerReplacement(n / 2 + 1).coerceAtMost(integerReplacement(n / 2))
} else{
1 + integerReplacement(n / 2)
}
}
方法2:
var map = HashMap<Int,Int>()
fun integerReplacement(n: Int): Int {
if (n == 1) return 0
if (!map.containsKey(n)){
if (n % 2 != 0) {
map[n] = 2 + integerReplacement(n / 2 + 1).coerceAtMost(integerReplacement(n / 2))
} else if (n != 1) {
map[n] = 1 + integerReplacement(n / 2)
}
}
return map[n]!!
}
总结
1.注意这个边界情况 不然产生了负数 可以一直除下去 导致stackOverFlow
2.官方题解还有一种方法 不过太过于难于理解
我不希望真实项目中存在那种写法 可读性和可维护性太差
边栏推荐
- 直播app开发搭建,flutter 实现自适应、自动换行、相对布局
- The technical aspects of the byte have been passed, and the salary has been negotiated for 20K*13, but the result is still being brushed. I asked the HR why...
- Copper's emotion
- Why don't suggest you run in Docker Mysql?
- 分布式数据库难题(三):数据一致性
- 【渗透工具】浏览器数据导出工具
- Redis-基本介绍/linux下环境配置/配置文件
- 【集训DAY4】矩形【线段树】
- 【集训DAY5】快速排序【模拟】【数学】
- 蔚来杯2022牛客暑期多校训练营7 CFGJ
猜你喜欢
KingbaseGIS Jin Cang database using manual (6.3. Geometric object creation function)
基于 LSTM 的分布式能源发电预测(Matlab代码实现)
vmware Exsi 网卡配置
上交所实时行情文件汇总
使用C语言实现静态链表
selenium和驱动安装
Why don't suggest you run in Docker Mysql?
Digital wallets, red sea ecological rapid introduction of small programs can help capture device entry wisdom
工程 (七) ——PolarSeg点云语义分割
程序员从佩洛西窜访事件中可以学到什么?
随机推荐
JVM Memory and Garbage Collection - 10. Direct Memory
Creo5.0 introductory tutorial free material
巴比特 | 元宇宙每日必读:国内首个数字人产业专项支持政策发布,2025年北京数字人产业规模将破500亿元...
分布式数据库难题(二):数据复制
天猫全网商品详情封装接口
新开窗口 展示协议
构建平衡二叉树「建议收藏」
Description of AirFlow
断开和服务器共享连接的方法「建议收藏」
数字钱包红海角逐,小程序生态快速引入可助力占领智慧设备入口
深度剖析 Apache EventMesh 云原生分布式事件驱动架构
selenium和驱动安装
dlopen failed: library "libtaml.so" not found
Golden Warehouse Database KingbaseGIS User Manual (6.4. Geometry Object Access Function)
为什么不建议你在 Docker 中跑 Mysql ?
工程 (七) ——PolarSeg点云语义分割
NTP SERVICE TASK 在GWserver配置、启用NTP服务,为当前环境提供时钟同步服务,Client主机可以从该服务器同步时间。
dlopen failed: library “libtaml.so“ not found
KingbaseGIS Jin Cang database using manual (6.3. Geometric object creation function)
《动手学深度学习》(八) -- 多尺度标检测和单发多框检测