From eb17c57bf3c0c3c5785568614073800866770f3f Mon Sep 17 00:00:00 2001 From: ironartisan Date: Mon, 30 Aug 2021 10:23:08 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A00134.=E5=8A=A0=E6=B2=B9?= =?UTF-8?q?=E7=AB=99Java=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index 0befd085..bee909c3 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -200,6 +200,7 @@ public: Java: ```java +// 解法1 class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int sum = 0; @@ -221,7 +222,26 @@ class Solution { } } ``` - +```java +// 解法2 +class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + int curSum = 0; + int totalSum = 0; + int index = 0; + for (int i = 0; i < gas.length; i++) { + curSum += gas[i] - cost[i]; + totalSum += gas[i] - cost[i]; + if (curSum < 0) { + index = (i + 1) % gas.length ; + curSum = 0; + } + } + if (totalSum < 0) return -1; + return index; + } +} +``` Python: ```python class Solution: