From c49dd3b1595fe4b8e2adb991b0882a78774ca32f Mon Sep 17 00:00:00 2001 From: Violet_Fu <156555169+iamziqian@users.noreply.github.com> Date: Tue, 30 Jul 2024 13:21:10 -0700 Subject: [PATCH] =?UTF-8?q?Update=200134.=E5=8A=A0=E6=B2=B9=E7=AB=99.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0134.加油站的Java解法三 --- problems/0134.加油站.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index c88b43b1..1329bd9a 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -249,6 +249,29 @@ class Solution { } } ``` +``` +// 解法3 +class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + int tank = 0; // 当前油量 + int totalGas = 0; // 总加油量 + int totalCost = 0; // 总油耗 + int start = 0; // 起点 + for (int i = 0; i < gas.length; i++) { + totalGas += gas[i]; + totalCost += cost[i]; + + tank += gas[i] - cost[i]; + if (tank < 0) { // tank 变为负数 意味着 从0到i之间出发都不能顺利环路一周,因为在此i点必会没油 + tank = 0; // reset tank,类似于题目53.最大子树和reset sum + start = i + 1; // 起点变为i点往后一位 + } + } + if (totalCost > totalGas) return -1; + return start; + } +} +``` ### Python 暴力法