zoukankan      html  css  js  c++  java
  • 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.

    思路:这道题可以基于最大字数列和的思想来解题,每次循环累加和存油量与耗油量只差分别记录两次,如果这次循环的差和小于零,则start记录这个点的下一个,并且将上述的其中一个变量置零,进行下次循环。如果循环下来,上述差额的累加和小于零的话,说明无法完成旅程。反之,返回start,记为开始旅程的起点。

    class Solution {
    public:
        int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
            if(gas.size()==0)
                return 0;
            int sum=0;
            int diff_sum=0;
            int result=0;
            for(int i=0;i<gas.size();i++)
            {
                sum+=gas[i]-cost[i];
                diff_sum+=gas[i]-cost[i];
                if(sum<0)
                {
                    result=(i+1)%gas.size();
                    sum=0;
                }
            }
            if(diff_sum<0)
                return -1;
            return result;
        }
    };
  • 相关阅读:
    java——对象学习笔记
    ORACLE中如何查看分区表信息
    postgresql相关系统表查询
    oracle系统表查询
    linux shell常用函数,ps
    文本文件合并
    nginx多版本PHP配置
    webuploader实现文件上传
    open abc.txt: The system cannot find the file specified
    PHP在线批量下载文件
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3713057.html
Copyright © 2011-2022 走看看