[leetcode] 134. Gas Station 解题报告

题目链接: https://leetcode.com/problems/gas-station/

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.


思路: 一次遍历, 记录下当前累计还剩下多少燃料, 如果燃料为负, 那么就从下一个位置重新开始计数, 并且将之前欠下的多少记录下来, 如果最终遍历完数组剩下的燃料足以弥补之前不够的, 那么就可以到达, 并返回最后一次开始的位置.否则就返回-1.

代码如下:

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int total = 0, left = 0, index = 0;
        for(int i =0; i< gas.size(); i++)
        {
            left += gas[i] - cost[i];
            if(left < 0)
            {
                index = i+1;
                total += left;
                left = 0;
            }
        }
        total += left;
        return total>=0?index:-1;
    }
};
参考: https://leetcode.com/discuss/69335/my-one-pass-solution

你可能感兴趣的:(LeetCode,greedy)