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
  • 相关阅读:
    Mysql常用命令
    Centos7初始配置
    centos7配置mysql
    CentOS7 配置阿里云yum源
    Dockerfile
    Centos7部署hadoop 3
    Windows10安装docker
    centos7安装docker
    大数据与分布式架构
    Centos7单主机部署 LAMP + phpmyadmin 服务
  • 原文地址:https://www.cnblogs.com/superzrx/p/3350377.html
Copyright © 2011-2022 走看看