10.25筆記
阿新 • • 發佈:2021-10-25
在一條環路上有N個加油站,其中第i個加油站有汽油gas[i]升。
你有一輛油箱容量無限的的汽車,從第 i 個加油站開往第 i+1個加油站需要消耗汽油cost[i]升。你從其中的一個加油站出發,開始時油箱為空。
如果你可以繞環路行駛一週,則返回出發時加油站的編號,否則返回 -1。
說明:
如果題目有解,該答案即為唯一答案。
輸入陣列均為非空陣列,且長度相同。
輸入陣列中的元素均為非負數。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/gas-station
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航class Solution { public static int canCompleteCircuit(int[] gas, int[] cost) { int index = 0; int n = gas.length; /** * 列舉每一個出發點 */ while (index < n) { /** * 當前出發點所能到達的節點數 */ int cnt = 0; /** * 當前出發點所積攢的油量 */ int sum = 0; while (cnt < n) { int i = (index + cnt) % n; sum += gas[i] - cost[i]; if (sum < 0) { break; } cnt++; } if (cnt == n) { return index; } else { /** * 比如index = 0, cnt = 3 * 那麼 1-3為出發點的肯定不可以 */ index = index + cnt + 1; } } return -1; } }