[leetcode_134]Gas Station

100题了~纪念一下。
先求是否有可行解。
然后从每个节点出发。找到第一个能到底部的节点。
AC了。个人认为想法对的。但是不肯定。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;

        int now = 0;
        int i = 0;
        ans = 0;
        while(i < gas.size()) {
            now += gas[i] - cost[i];
            if(now < 0) {
                i++;
                now = 0;
                ans = i;
            }
            else
                i++;
        }
        return ans;
    }
};
Licensed under CC BY-NC-SA 4.0