Gas Station

来源:互联网 发布:java easyui tree例子 编辑:程序博客网 时间:2024/05/22 01:48

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

题目: 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.

Solution: 令left[i] = gas[i] - cost[i],sum[i : j] = left[i] + left[i+1] +… +left[j]. 现在假设题目有解,并假设车从站i开出,能到达站k,但在到达站k+1的途中没有了,这说明sum[i : k+1] < 0, 但这时,对任意的j,当i <= j <= k,sum[i : j] >= 0都是成立的。所以,由于只有唯一的解,站i~k都不可能是起始站,因为对任意的t,当i <= t <= k,都有sum[t : k+1] < 0。这时,因为假设有解,我们只需继续往后遍历站k+1。直到找到一个站点x,使得站点x符合sum[x : gas.size()-1] > 0,这时,站点x可能是解,只是可能,因为前面假设了题目有解。
那怎么确定题目是否有解?若题目有解,那么sum[0 : gas.size()-1]肯定大于或等于0,而题目又保证有唯一解,那上述的站点x就是题目的解。若小于0,那么题目肯定无解。

class Solution {public:    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        int n = gas.size();        int sum = 0, total = 0;        int start_index = 0;        for (int i = 0; i < n; ++i) {            sum += (gas[i] - cost[i]);            total += (gas[i] - cost[i]);            if (sum < 0) {                start_index = i + 1;                sum = 0;            }        }        return total < 0 ? -1 : start_index;    }};

复杂度: 时间复杂度为O(n)。

原创粉丝点击