leetcode-每日一题2021.11.19 整数替换

题目

力扣

思路一

递归,偶数就把n替换成n/2,数目+1;奇数就把n替换成n/2向下取整递归和n/2+1向下取整递归的最小值,数目+2.

代码一

class Solution {
public:
    int integerReplacement(int n) {
        if(n==1) return 0;
        if(n&1)
            return 2+min(integerReplacement(n/2),integerReplacement(n/2+1));
        return 1+integerReplacement(n/2);
    }
};

思路二 记忆化搜索

利用哈希表把递归得到的次数信息存下来,以空间换时间。

代码二

class Solution {
public:
    unordered_map<int,int> cnt;
    int integerReplacement(int n) {
        if(n==1) return cnt[1]=0;
        if(cnt.count(n))
            return cnt[n];
        if(n&1)
            return cnt[n]=2+min(integerReplacement(n/2),integerReplacement(n/2+1));
        return cnt[n]=1+integerReplacement(n/2);
    }
};

思路三 贪心(位运算)

偶数就右移一位,奇数要分两种情况。第一种情况次低位是1,+1,第二种情况次低位是0,-1.这个数是3是个特例,-1可以更快得到结果。

代码三

class Solution {
public:
    int integerReplacement(int _n) {
        long n=_n;
        int cnt=0;
        while(n!=1){
            if(!(n&1))
                n>>=1;
            else{
                if(n!=3&&((n>>1)&1)==1)
                    n++;
                else
                    n--;
            }
            cnt++;
        }
        return cnt;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值