leetcode 134. Gas Station

来源:互联网 发布:cad软件手机版 编辑:程序博客网 时间:2024/06/11 17:37

1、题目

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.
环形公路加油站问题。一条环形公路上有N个加油站,加油站i的油量为gas[i],从加油站i到i+1的耗油为cost[i]。汽车的油箱容量不限。求从哪个站点出发可以跑完全程,不存在则返回-1。

Note:
The solution is guaranteed to be unique.

2、分析

gas[i]-cost[i]等于从i到i+1还剩的油量。
int current 记录当前剩油量
int total 记录总剩油量
从0站点开始遍历:
对每站gas[i]-cost[i]求和。current+=gas[i]-cost[i],total+=gas[i]-cost[i]
如果累计剩油量current<0,则0-i的所有站点都不可能作为出发点。(因为跑不到下一站就没油了)。把i+1设置为新出发点,current重置。

遍历结束后:如果total<0,说明总体是跑不到的,返回-1;否则返回找到的起始点。

3、代码

int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {    int total = 0;//总剩油量    int current = 0;//当前剩油量    int start = 0;    for (int i = 0; i < gas.size(); i++) {        current += gas[i] - cost[i];        total += gas[i] - cost[i];        if (current < 0)//i和之前的所有站点不能成为起始点        {            start = i + 1;            current = 0;        }    }    return total < 0 ? -1 : start;}
原创粉丝点击