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

    1 如果总的gas - cost小于零的话,那么没有解返回-1。(总gas> 总cost 是有解的充分便要条件,要是解这道题的关键)

    2 如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点(存在gas-cost<0,剩下的必然存在gas-cost>0)。

    3 选择最佳出发点后,判断从这点出发能否环行一圈。

    class Solution {
    public:
        int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
            int len = gas.size();
            int res = -1;
            int res_gas = 0;
            int start_station = 0;
            int total_res = 0;
            for(int i =0 ; i < len; i++)
            {
                res_gas += (gas[i] - cost[i]) ;
                total_res += (gas[i] - cost[i]) ;
                if(res_gas < 0)
                {
                    start_station = i+1;
                    res_gas = 0;
                }
            }
            if(total_res >= 0)
            {
                res = start_station;
            }
            return res;
            
        }
    };
    

      

  • 相关阅读:
    解决vue项目route使用history模式,tomcat部署刷新url 404问题
    更新
    Mac Anaconda 安装
    Mac python 环境配置
    Mac Python PyQt5 环境搭建
    Python 百分比计算
    Python __init__.py 文件使用
    Python redis 简单介绍
    python Django 创建应用
    python Django 项目创建
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4551914.html
Copyright © 2011-2022 走看看