zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    2021年2月22
    2021年2月21
    2021年2月20
    2021年2月19
    动态添加titie属性
    根据内容改变文字颜色!
    自定义弹出层!
    来回切换图标以及文字
    20180831xlVBA_WorksheetsCosolidate
    20180830xlVBA_合并计算
  • 原文地址:https://www.cnblogs.com/superzrx/p/3350377.html
Copyright © 2011-2022 走看看