Gas Station

来源:互联网 发布:淘宝客现状 编辑:程序博客网 时间:2024/06/06 19:13

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 gastank and it costs cost[i] of gas to travel from station i to its next station (i+1). Youbegin the journey with an empty tank at one of the gas stations.

Return the starting gas station's indexif you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

思路:首先想到的方法就是On^2)遍历两遍。搜了一下发现有更巧妙的方法,用两个变量来控制。第一个变量total负责一直累加gas[i]-cost[i],如果加到最后total>=0,说明肯定全局是有解的,但是不能判断出来到底是从哪里出发导致的有解;第二个变量sum就非常重要了,通过它来寻找start point在哪里。找的思路很简单,肯定是在sum<0的后一个index开始,这个要好好揣摩一下。Sum不关注到底有没有全局解,它只负责记录从i=0i=n-1这个过程中最后一个导致sum<0index。如果最后total>=0,那么index+1就为正确的起始点;如果最后total<0,那么sum记录的index也没用了,就是返回-1

Refhttp://blog.csdn.net/lbyxiafei/article/details/12183461

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


0 0
原创粉丝点击