思路一:dfs (时间复杂度:O(logn),即n二进制中1的个数)
奇数有两个分支,对于偶数只有两个分支。
class Solution {
public:
unordered_map<int, int> umap;
int integerReplacement(int n) {
if (n == 1) return 0;
if (umap.count(n)) return umap[n];
if (n % 2) {
umap[n] = 2 + min(integerReplacement(n / 2 + 1), integerReplacement(n / 2)); //
}else {
umap[n] = 1 + integerReplacement(n / 2);
}
return umap[n];
}
};
注意:当n为INT_MAX时,n+1会越int,由于
n为奇数时,(n+1)/2等价于n/2+1,都表示n/2向上取整,(n-1)/2等价于n/2,都表示n/2向下取整。
所以这里直接走两步(+1后为偶数,直接/2),所以直接写成n/2+1就不会越界了。
思路二:看到最短直接想到用广度搜索bfs
class Solution {
public:
int integerReplacement(int n) {
queue<long long> q;
unordered_set<long long> ust;
q.push(n);
ust.insert(n);
int layer = 0;
while (!q.empty()) {
int m = q.size();
for (int i = 0; i < m; ++i){
long long frt = q.front();
q.pop();
if (frt == 1) return layer;
if (frt & 1) {
if (!ust.count(frt + 1)) q.push(frt + 1);
if (!ust.count(frt - 1)) q.push(frt - 1);
ust.insert(frt + 1);
ust.insert(frt - 1);
}else {
if (!ust.count(frt / 2)) q.push(frt / 2);
ust.insert(frt / 2);
}
}
layer++;
}
return -1;
}
};
学到的东西:
1:学习代码:layer的处理
int layer = 0;
while (q.empty()) {
int n = q.size();
for (int i = 0; i < n; ++i) {
int frt = q.front();
q.pop();
for (...) {
q.push();
}
}
layer++;
}
2:queue的元素类型为long long,防止n为INT_MAX时,n+1越int的界。
3:在队列push时,可以加个记忆化,在之前push过的下一次就不进行push了。
思路三:贪心
具体思路:XX11(末尾连续1的数目大于2)时,用(n+1)/2,否则用(n-1)/2
证明如下:
class Solution {
public:
int integerReplacement(int n) {
int ans = 0;
while (n != 1) {
if ((n & 1) == 0) { //
n >>= 1;
ans++;
}else if ((n & 3) == 1) {
ans += 2;
n = (n - 1) >> 1;
}else {
if (n == 3) return ans + 2;
ans += 2;
n = (n >> 1) + 1; //
}
}
return ans;
}
};
易错点
1:(n & 1) == 0 不能写成 n&1==0,位运算的优先级较低。
2:(n+1)/2会越界->写成n/2+1