贪心算法 day08(加油站+单调递增的数字+坏了的计算机)

目录

1.加油站

2.单调递增的数字

3.坏了的计算器


1.加油站

链接:. - 力扣(LeetCode)

思路:

gasindex - costindex,ret 表示的是在i位置开始循环时剩余的油量

a到达的最大路径假设是f那么我们可以得出 a + b + c + d + e +f < 0 那么从b开始的话到达f那也是小于0的无法循环(b是正数 即只能从正的位置开始循环)

代码:

复制代码
    public static int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length,step = 0;
        for (int i = 0; i < n; i++) {
            int ret = 0;
            for( step = 0; step < n;step++){
                int index = (step + i) % n;
                ret = ret + gas[index] - cost[index];
                if(ret < 0){
                    break;
                }
            }

            if(ret >= 0){
                return i ;
            }
//更新i要满足两个条件,首先是要step循环要结束,
//同时要判断i坐标下的ret小于0,即该位置下的最大step 
//同时如果 ret = 0时就需要再更新i坐标
            i = i +step;
        }
        return -1;
    }

2.单调递增的数字

链接:. - 力扣(LeetCode)

思路:

代码:

复制代码
class Solution {
       public int monotoneIncreasingDigits(int n) {
        char[] ch = Integer.toString(n).toCharArray();
        int l = ch.length,i = 0;
       while(i + 1 < l && ch[i] <= ch[i + 1]) i++;
       //第一种情况 数组都是单调递增的 i恰好是在l - 1的位置
        if(i == l - 1){
            return n;
        }
        //  如果出现连续数字都是相同的情况我们需要把相同的第一个数字减一其他的变为9就好
        while( i - 1 >= 0 && ch[i] == ch[i - 1])i--;
        ch[i] --;
        for(int j = i +1 ; j < l;j++){
            ch[j] = '9';
        }
        return Integer.parseInt(new String(ch));

    }
}

3.坏了的计算器

题目链接:991. 坏了的计算器 - 力扣(LeetCode)

题目给出的处理方式为-1和 *2 ,这里我们采用逆放思想此时的处理方式只有+1 和 /2,分两种情况讨论。

一种是 startValue >= target ,此时逆放推理由target变到startValue,要想增加只能+1.

例如 :startValue = 10 ,target = 4 ,target为偶数除以2只会离startValue越来越小,所以不管奇偶只要+1就好,处理次数为 startValue - target。

第二种 startValue < target ,此时逆反推理偶数先除2更优。target除2之后变小离startValue更近。

证明:x,k为偶数 x如果执行先+1操作 假设+k次之后再进行除2操作(最终必须除2因为 target 大于 startValue要变小)就需要执行(k+1)次操作变成(x+k)/2;

如果x先除2未达到startValue之后再进行+1操作 ,只需加k/2次,操作次数为(k/2+1);

假设:startValue = 3 ,target = 10,由target推理startValue,偶数target先除2变奇数+1target > startValue前提下 再除2。

代码:

复制代码
class Solution {
      public static int brokenCalc(int startValue, int target) {
        int count = 0;
        while (target > startValue){
            if( target% 2 == 0) target /= 2;
            else target += 1;
            count++;
        }
        return count+ startValue - target;
    }
}
相关推荐
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2122 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2123 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2123 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术3 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050733 天前
(一)小红的数组操作
算法·编程语言