###### tags: `LeetCode` `Medium` # LeetCode #134 [Gas Station](https://leetcode.com/problems/gas-station) ### (Medium) 在一條環路上有 N 個加油站,其中第 i 個加油站有汽油 gas[i] 升。 你有一輛油箱容量無限的的汽車,從第 i 個加油站開往第 i+1 個加油站需要消耗汽油 cost[i] 升。你從其中的一個加油站出發,開始時油箱為空。 如果你可以繞環路行駛一周,則返回出發時加油站的編號,否則返回 -1。 --- 若全部的gas和大於等於cost和, 則可以走完全程。 若某點到下一點的累積gas數量小於cost數量, 則該點不可能為起點。 --- ``` class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int start=0,curr=0,total=0; for(int i=0;i<gas.size();i++){ total+=(gas[i]-cost[i]); curr+=(gas[i]-cost[i]); if(curr<0){ start=i+1; curr=0; } } return total>=0?start:-1; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up