首页 > 编程语言 >#yyds干货盘点# LeetCode程序员面试金典:整数替换

#yyds干货盘点# LeetCode程序员面试金典:整数替换

时间:2024-01-14 23:01:04浏览次数:28  
标签:yyds return 示例 int 金典 替换 integerReplacement LeetCode 输入

题目

给定一个正整数 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

代码实现

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));
    }
}


标签:yyds,return,示例,int,金典,替换,integerReplacement,LeetCode,输入
From: https://blog.51cto.com/u_13321676/9242781

相关文章

  • leetcode 跳跃游戏
    classSolution{public:boolcanJump(vector<int>&nums){intn=nums.size();intcurrent_length=nums[0];if(n==1)returntrue;if(current_length==0)returnfalse;for(inti=1;i<n;i......
  • [刷题技巧] LeetCode238. 除自身以外数组的乘积
    题目描述思路:前缀/后缀乘积数组构造除自身以外数组的左边前缀乘积构造除自身以外数组的右边后缀乘积然后对应位置相乘方法一:classSolution{publicint[]productExceptSelf(int[]nums){intn=nums.length;//前缀乘积数组:leftProduct[i]表......
  • [刷题班] LeetCode1480. 一维数组的动态和
    题目描述思路:前缀和前缀和数组(prefixSum)的构造方法一:classSolution{publicint[]runningSum(int[]nums){int[]preSum=newint[nums.length];preSum[0]=nums[0];for(inti=1;i<nums.length;i++){preSum[i]......
  • [刷题班] LeetCode125. 验证回文串
    题目描述思路:左右指针只考虑数字和字母字母的话需要全部转化为小写然后使用左右指针判断是否是回文串方法一:classSolution{publicbooleanisPalindrome(Strings){List<Character>list=newArrayList<>();for(charc:s.toCharArray()){......
  • [刷题班] LeetCode11. 盛最多水的容器
    题目描述思路:左右指针方法一:暴力,超出时间限制模拟所有情况,记录最大的体积值。体积=Math.min(height[i],height[j])*(j-i)classSolution{publicintmaxArea(int[]height){intres=Integer.MIN_VALUE;for(inti=0;i<height.leng......
  • [刷题班] LeetCode27. 移除元素
    题目描述思路:快慢指针slow指针:其前面都是数值不等于val的元素。fast指针:用于遍历。方法一:classSolution{publicintremoveElement(int[]nums,intval){intslow=0,fast=0;for(;fast<nums.length;fast++){if(nums[fas......
  • [刷题班] LeetCode344. 反转字符串
    题目描述思路:左右指针方法一:classSolution{publicvoidreverseString(char[]s){intleft=0,right=s.length-1;while(left<right){chartemp=s[left];s[left]=s[right];s[right]=temp;......
  • [刷题班] LeetCode80. 删除有序数组中的重复项II
    题目描述思路:快慢指针slow指针指向已经处理元素的下一个位置因为数组有序,如果nums[fast]==nums[slow-2],那么nums[fast]肯定等于nums[slow-1],那么此时这个数就出现了三次。此时slow保持不变,fast继续遍历。关键:nums[fast]!=nums[slow-2]方法一:classSolution{......
  • [刷题班] LeetCode26. 删除有序数组中的重复项
    题目描述思路:快慢指针slow指针:指向已经处理的区域(没有重复元素)的最后一个位置fast指针:指向当前正在处理的元素方法一:classSolution{publicintremoveDuplicates(int[]nums){intslow=0,fast=0;for(;fast<nums.length;fast++){......
  • # yyds干货盘点 # 盘点一个AI解答疑难代码的问题
    大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas代码解读的问题,问题如下:df_in=df[df['入/出'].eq('入')],我也不懂eq啥意思?感觉这代码还可以写成df[df['入/出']=='入'],这两段一个意思吧。答:eq就是=,就是你说的这个。二、实现过程后来【论草莓如......