397.整数替换
1. 思路
思路很简单,进行求奇偶数变为1的最小次数,首先能够想到DFS;递归操作,递归很容易就能想出来:
首先最基本的
1.条件返回值 if(n == 1)
2.然后就是偶数一直递归值条件返回值
3.进行次数累计
2.遇到难点
没考虑到整数型溢出问题 整数最大值为 2147483647 ,但是如果记性基数的+1操作会致使整数型数据溢出,因此需要进行消除溢出情况。
在进行奇数的操作的时候 可以直接 n/2 + 1 和 n/2操作
3.结果
class Solution {
public int integerReplacement(int n) {
//如果是偶数就是最小次数
//只有出现奇数的时候 才会出现哪种方式是最小次数
int sum = 0;
if (n == 1) {
return 0;
}
if (n % 2 == 0) {
//判断实际数还是偶数
sum += integerReplacement(n / 2) + 1;
} else {
sum += 2 + Math.min(integerReplacement(n/2+1), integerReplacement(n/2));
}
return sum;
// if (n == 1) {
// return 0;
// }
// if (n % 2 == 0) {
// return 1 + integerReplacement(n / 2);
// }
// return 2 + Math.min(integerReplacement(n / 2), integerReplacement(n / 2 + 1));
}
}
4.参考其他思路
记忆化搜索
有点像动态规划中的字典,进行存储已经计算过的值,保证不会重复计算,提高效率
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public int integerReplacement(int n) {
if (!map.containsKey(n)) {
if (n % 2 == 0) {
//判断实际数还是偶数
map.put(n, integerReplacement(n / 2) + 1);
} else {
map.put(n, Math.min(integerReplacement(n / 2 + 1), integerReplacement(n / 2)) + 2);
}
}
return map.get(n);
}
复杂度分析
时间复杂度:O(\log n)O(logn)。
空间复杂度:O(\log n)O(logn),记忆化搜索需要的空间与栈空间相同,同样为 O(\log n)O(logn)
贪心
思路与算法
class Solution {
public int integerReplacement(int n) {
int ans = 0;
while (n != 1) {
if (n % 2 == 0) {
++ans;
n /= 2;
} else if (n % 4 == 1) {
ans += 2;
n /= 2;
} else {
if (n == 3) {
ans += 2;
n = 1;
} else {
ans += 2;
n = n / 2 + 1;
}
}
}
return ans;
}
}
总结:
学习慢慢积累,修炼好内功