標籤:leetcode 演算法 面試
【題目】
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station‘s index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
【題意】
有N個節油站構成一個環狀路徑,每個加油張能夠加油的量由gas[i]給出,車從i站駛到下一站i+1需要消耗的油量由cost[i+1]給出
找出從那個加油站始發能夠正好跑完一圈。返回加油站的索引位,如果找不到返回-1
題目保證,解是唯一的。
【思路】
1. 先計算要行駛到下一個加油站,每站至少需要剩油多少,即能夠從當前節點可達下一站的臨界條件
2. 選擇那些剩油需求<=0的加油站作為起點,依次判斷
【代碼】
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int size=gas.size(); if(size==0)return -1;//注意size=1也是需要考慮。這裡好大一個坑,竟然真有自己駛到自己這種荒謬的case vector<int> gasRemainNeed; for(int i=0; i<size; i++){ gasRemainNeed.push_back(cost[i]-gas[i]); } int start=0;int p=start;int remain=0; while(start<size){ while(remain>=gasRemainNeed[p%size]){ //判斷當前汽車的剩油量夠不夠跑到下一站,如果能跑就不斷跑下去,直到跑不下去為止 remain-=gasRemainNeed[p%size];//計算駛到下一站的剩油量 p++;//遊標指向下一站 if(p%size==start)return start; //如果已經跑完一圈,返回 }//start向後移動,並不斷更新油箱中的剩油,直到剩油量能使車從p駛到p+1while(start<size && start<p && remain<gasRemainNeed[p%size]){remain+=gasRemainNeed[start];start++;}//如果p指標正好指到start上,則兩個遊標同時向後移動一位if(start==p){start++; p++;} } return -1; }};