当前位置:网站首页>算法---整数替换(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.官方题解还有一种方法 不过太过于难于理解
我不希望真实项目中存在那种写法 可读性和可维护性太差
边栏推荐
猜你喜欢

深入理解Aarch64内存管理

CST Studio Suite 2021 software installation package and installation tutorial
![[SUCTF 2019]CheckIn (.htaccess和.user.ini)](/img/43/9e5a501410d2b957969b713d4fe209.png)
[SUCTF 2019]CheckIn (.htaccess和.user.ini)

arm-4-裸板开发

Eureka自我保护

Dry goods!Towards robust test-time adaptation

【集训DAY4】矩形【线段树】

framework源码读后感

Digital wallets, red sea ecological rapid introduction of small programs can help capture device entry wisdom

KingbaseGIS Jin Cang database using manual (6.3. Geometric object creation function)
随机推荐
【SSL集训DAY2】有趣的数【数位DP】
YOLOV5 study notes (7) - training your own data set
Eureka protects itself
新开窗口 展示协议
漫谈缺陷管理的自动化实践方案
labelme标注的json标签转txt格式
Golden Warehouse Database KingbaseGIS User Manual (6.5. Geometry Object Editing Function)
博弈小游戏
【集训DAY5】堆箱子【数学】
数字孪生智慧制造生产线项目实施方案,平台认知与概念
dlopen failed: library "libtaml.so" not found
Creo5.0 introductory tutorial free material
ES6 从入门到精通 # 13:数组的扩展方法二
为什么不建议你在 Docker 中跑 Mysql ?
ES6 从入门到精通 # 14:迭代器 Iterator 的用法
redis分布式锁代码示例
服务发现@EnableDiscoveryClient
FreeRTOS任务基础
JVM内存和垃圾回收-10.直接内存
ES6 从入门到精通 # 15:生成器 Generator 的用法