• LeetCode-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.

    遇到一个无法到达的站则把起点向前推,如果推了一圈则说明无法到达

    class Solution {
    public:
        int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            int bal=0;
            int start=0;
            for(int i=0;i<gas.size();i++){
                int pos=start+i;
                if(pos>=gas.size())pos-=gas.size();
                bal+=gas[pos];
                bal-=cost[pos];
                while(bal<0){
                    start--;
                    if(start<0)start=gas.size()-1;
                    i++;
                    if(i==cost.size())return -1;
                    bal+=gas[start];
                    bal-=cost[start];
                }
            }
            return start;
        }
    };
    View Code
  • 相关阅读:
    浅谈Tarjan算法及思想
    浅谈前向星
    线段树初步
    树状数组的简单运用
    字典树(trie树)的指针简单实现pascal
    排序专辑
    POJ 2155 Matrix (矩形)
    区间动态规划
    hdu-2795 Billboard---线段树
    hdu-1754 I Hate It---线段树模板题
  • 原文地址:https://www.cnblogs.com/superzrx/p/3350377.html
Copyright © 2020-2023  润新知