leetcode-貪心-134

/** * <p>在一條環路上有 <code>n</code>&nbsp;個加油站,其中第 <code>i</code>&nbsp;個加油站有汽油&nbsp;<code>gas[i]</code><em>&nbsp;</em>升。</p> * * <p>你有一輛油箱容量無限的的汽車,從第<em> </em><code>i</code><em> </em>個加油站開往第<em> </em><code>i+1</code><em>&nbsp;</em>個加油站需要消耗汽油&nbsp;<code>cost[i]</code><em>&nbsp;</em>升。你從其中的一個加油站出發,開始時油箱爲空。</p> * * <p>給定兩個整數數組 <code>gas</code> 和 <code>cost</code> ,如果你可以繞環路行駛一週,則返回出發時加油站的編號,否則返回 <code>-1</code> 。如果存在解,則 <strong>保證</strong> 它是 <strong>唯一</strong> 的。</p> * * <p>&nbsp;</p> * * <p><strong>示例&nbsp;1:</strong></p> * * <pre> * <strong>輸入:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2] * <strong>輸出:</strong> 3 * <strong>解釋: * </strong>從 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 可爲起始索引。</pre> * * <p><strong>示例 2:</strong></p> * * <pre> * <strong>輸入:</strong> gas = [2,3,4], cost = [3,4,3] * <strong>輸出:</strong> -1 * <strong>解釋: * </strong>你不能從 0 號或 1 號加油站出發,因爲沒有足夠的汽油可以讓你行駛到下一個加油站。 * 我們從 2 號加油站出發,可以獲得 4 升汽油。 此時油箱有 = 0 + 4 = 4 升汽油 * 開往 0 號加油站,此時油箱有 4 - 3 + 2 = 3 升汽油 * 開往 1 號加油站,此時油箱有 3 - 3 + 3 = 3 升汽油 * 你無法返回 2 號加油站,因爲返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。 * 因此,無論怎樣,你都不可能繞環路行駛一週。</pre> * * <p>&nbsp;</p> * * <p><strong>提示:</strong></p> * * <ul> * <li><code>gas.length == n</code></li> * <li><code>cost.length == n</code></li> * <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> * <li><code>0 &lt;= gas[i], cost[i] &lt;= 10<sup>4</sup></code></li> * </ul> * <div><div>Related Topics</div><div><li>貪心</li><li>數組</li></div></div><br><div><li>👍 1005</li><li>👎 0</li></div> */ //leetcode submit region begin(Prohibit modification and deletion) class Solution { //如果 從1出發到4 剩下的油小於0,那麼 2,3也無法走到。 public int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; int sum = 0; for (int i = 0; i < n; i++) { sum += gas[i] - cost[i]; } if (sum < 0) { return -1; } int tank = 0; int start = 0; for (int i = 0; i < n; i++) { tank += gas[i] - cost[i]; if (tank < 0) { tank = 0; start = i + 1; } } return start == n ? 0 : start; } } //leetcode submit region end(Prohibit modification and deletion)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章