134. Gas Station

来源:互联网 发布:显示登录成功和链接php 编辑:程序博客网 时间:2024/06/06 02:52
  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.

    Note:
    The solution is guaranteed to be unique.

  2. 解决思路
    其实就是找到从哪个点开始遍历,和一直不为负数。这里有一个问题就是只能够正向走,即i 只能走向i+1。所以我们可以假定从最后一个节点开始走,如果和为正,就正向走,如果和为负数,则将开始节点倒退,一直倒退到和为正位置。则最后倒退到不能倒退的节点就是我们要找的目标节点,如果最后得和还是负数,则不存在这样的节点。

  3. 代码

class Solution {public:    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {        int n = gas.size();        if (n == 1) {            if (gas[0] >= cost[0])                return 0;            else                return -1;        }        int end = n - 1, start = 0;        int sum = gas[end]-cost[end];        while(end > start) {            if (sum > 0) {                sum += gas[start]-cost[start];                ++start;            } else {                --end;                sum += gas[end]-cost[end];            }        }        return sum >= 0 ? end:-1;    }};
0 0
原创粉丝点击