首页 » 编程之美 » 正文

[leetcode_134]Gas Station

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 &lt; 0)return ans;</p>

<pre><code>    int now = 0;
    int i = 0;
    ans = 0;
    while(i &amp;lt; gas.size()) {
        now += gas[i] - cost[i];
        if(now &amp;lt; 0) {
            i++;
            now = 0;
            ans = i;
        }
        else
            i++;
    }
    return ans;
}
</code></pre>

<p>};

发表评论