Leetcode134:加油站

文章目录

题目描述

在这里插入图片描述示例 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 可为起始索引。


示例 2:
输入:
gas = [2,3,4]
cost = [3,4,3]

输出: -1

解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。

思路分析

在这里插入图片描述

	public static int canCompleteCircuit1(int[] gas, int[] cost) {
		int start=0,total=0,tank=0;
		for (int i = 0; i < gas.length; i++) {
			tank+=gas[i]-cost[i];
			if (tank<0) {
				start=i+1;
				total+=tank;//到下一站差多少油总共还差多少油
				tank=0;
			}
		}
		return (total+tank<0)?-1:start;
	}

在这里插入图片描述

	public static int canCompleteCircuit(int[] gas, int[] cost) {
		int n = gas.length;// 有多少个加油站

		int total_tank = 0;//邮箱里剩下的油
		int curr_tank = 0;//记录当前油箱里剩余的总油量
		int starting_station = 0;//表示第0号加油站
		for (int i = 0; i < n; i++) {
			total_tank += gas[i] - cost[i];
			curr_tank += gas[i] - cost[i];
			// 如果一个车不可以到达这儿
			if (curr_tank < 0) {
				// 接下一站作为出发站
				starting_station = i + 1;
				// 从空罐开始
				curr_tank = 0;
			}
		}
		return total_tank >= 0 ? starting_station : -1;
	}
发布了88 篇原创文章 · 获赞 27 · 访问量 5908

猜你喜欢

转载自blog.csdn.net/weixin_43362002/article/details/104372897