贪心算法(11)(java)加油站

题目:在一条环路上有n个加油站,其中第i个加油站有汽油 gasi升.。

你有一辆油箱容量无限的的汽车,从第i个加油站开往第i+1个加油站需要消耗汽油 costi升。你从其中的一个加油站出发,开始时油箱为空。

给定两个整数数组 gas 和 cost,如果你可以按顺而环招行驶一周,则返回出发时加油站的编号,否则返回-1。如果存在解,则保证它是唯一的.

示例1:

输入:gas = 1,2,3,4,5,cost = 3,4,5,1,2

输出:3

解释:

从3号加油站(索引为3 处)出发,可获得4升汽油。此时油箱有 =0+4=4升汽油

开往 4号加油站,此时油箱有4-1+5=8升汽油

开往0号加油站,此时油箱有8-2+1=7升汽油

开往 1号加油站,此时油箱有7-3+2=6升汽油

开往 2 号加油站,此时油箱有6-4+3=5升汽油

开往 3号加油站,你需要消耗5升汽油,正好足够你返回到3号加油站。

因此 ,3可为起始索引。

解法1:暴力->枚举

1.依次枚举所有起点;

2.从起点开始,模拟一遍加油的流程即可

java 复制代码
public class Solution1 {
    public int canCompleteCircuit(int[]gas,int[] cost)
    {
        int n=gas.length;
        for(int i=0;i<n;i++)//依次枚举所有的起点
        {
            int rest=0;//统计净收益
            for(int step=0;step<n;step++)//枚举向后走的步数
            {
                int index=(i+step)%n;//走step不之后的下标
                rest=rest+gas[index]-cost[index];
                if(rest<0)
                {
                    break;
                }
            }
            if(rest>=0)
            {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Solution1 solution1=new Solution1();
        int []gas={1,2,3,4,5};
        int []cost={3,4,5,1,2};
        System.out.println(solution1.canCompleteCircuit(gas,cost));
    }
}

解法2:贪心:时间复杂度O(n):

java 复制代码
public class Solution2 {
        public int canCompleteCircuit(int[]gas,int[] cost)
        {
            int n=gas.length;
            for(int i=0;i<n;i++)//依次枚举所有的起点
            {
                int rest=0;//统计净收益
                int step=0;
                for(;step<n;step++)//枚举向后走的步数
                {
                    int index=(i+step)%n;//走step不之后的下标
                    rest=rest+gas[index]-cost[index];
                    if(rest<0)
                    {
                        break;
                    }
                }
                if(rest>=0)
                {
                    return i;
                }
                i=i+step;//贪心优化
            }
            return -1;
        }

        public static void main(String[] args) {
            Solution2 solution2=new Solution2();
            int []gas={1,2,3,4,5};
            int []cost={3,4,5,1,2};
            System.out.println(solution2.canCompleteCircuit(gas,cost));
        }
    }
相关推荐
JieE21220 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack201 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树1 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050732 天前
(一)小红的数组操作
算法·编程语言
怕浪猫2 天前
Electron 系列文章封面图
算法·架构·前端框架