2021.11.19LeetCode每日一题——整数替换

目录

整数替换

描述

示例 1

示例 2

示例 3

提示

方法:递归

方法二:记忆搜索


整数替换

描述

给定一个正整数 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 \le n \le 2^{31} - 1

方法:递归

class Solution {
    public int integerReplacement(int n) {
        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));
    }
}

方法二:记忆搜索

我们给上述递归过程中求解出来的值用map集合进行记录,后续需要的时候先从集合中查找,没找到再用递归方法求解。

class Solution {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    public int integerReplacement(int n) {
        if (n == 1) return 0;
        if (!map.containsKey(n)){
            if (n % 2 == 0) {
                map.put(n,1+integerReplacement(n/2));//求解n/2的次数,并记录到map集合中
            }else{
                map.put(n,2+Math.min(integerReplacement(n / 2), integerReplacement(n / 2 + 1)));//将(n+1)/2和(n-1)/2一起执行了
            }
        }
        return map.get(n);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39478524/article/details/121414324
今日推荐