100题了~纪念一下。
先求是否有可行解。
然后从每个节点出发。找到第一个能到底部的节点。
AC了。个人认为想法对的。但是不肯定。
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int ans = -1; int sum = 0; for(int i = 0;i < gas.size();i++) { sum += gas[i]; sum -= cost[i]; } if(sum < 0)return ans;</p> <pre><code> int now = 0; int i = 0; ans = 0; while(i &lt; gas.size()) { now += gas[i] - cost[i]; if(now &lt; 0) { i++; now = 0; ans = i; } else i++; } return ans; } </code></pre> <p>};