leetcode - Gas Station
2013-11-23 23:30 张汉生 阅读(156) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 if (gas.size()<=0) 7 return -1; 8 if (gas.size()==1){ 9 if (gas[0]>=cost[0]) 10 return 0; 11 else return -1; 12 } 13 int n = gas.size(); 14 int remainChecks = n; 15 int curSum = 0; 16 for (int i=0; i<n; i++){ 17 int index = -1; 18 //cout << "start check: i= " << i << ",remain="<<remainChecks << ",curSum=" << curSum << endl; 19 while (remainChecks>0 && curSum>=0){ 20 index = (i+(n-remainChecks))%n; 21 curSum += gas[index] - cost[index]; 22 remainChecks--; 23 } 24 if (remainChecks==0 && curSum>=0) 25 return i; 26 curSum -= gas[i] - cost[i]; 27 remainChecks++; 28 } 29 return -1; 30 } 31 };