zoukankan      html  css  js  c++  java
  • 加油站

    加油站

    加油站

    1 题目

    在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] ,并且从第 i 个加油站前往第 i+1 个加油站需要消耗汽油 cost[i]

    你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。

    求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。

    注意事项

    数据保证答案唯一。

    2 样例

    现在有4个加油站,汽油量 gas[i]=[1, 1, 3, 1] ,环路旅行时消耗的汽油量 cost[i]=[2, 2, 1, 1] 。则出发的加油站的编号为2。

    3 挑战

    O(n)时间和O(1)额外空间

    4 思路

    public class Solution {
        /**
         * @param gas: an array of integers
         * @param cost: an array of integers
         * @return: an integer
         */
        public int canCompleteCircuit(int[] gas, int[] cost) {
            // write your code here
            int result = 0;
            int totalGas = 0;
            int curGas = 0;
            int remainedGas = 0;
            for (int i = 0; i < gas.length; i++) {
                curGas = gas[i] - cost[i];
                if (remainedGas < 0 && curGas >= 0) {
                    result = i;
                    remainedGas = 0;
                }
    
                remainedGas += curGas;
                totalGas += curGas;
            }
    
            if (totalGas < 0) {
                return -1;
            } else {
                return result;
            }
        }
    }
    

    Date: 2017-01-02 12:48

    Created: 2017-01-02 周一 13:24

    Validate

  • 相关阅读:
    if __name__ == '__main__' 用法理解
    VSCode 使用
    sys.argv用法简介
    [Python3] RSA的加解密和签名/验签实现 -- 使用pycrytodome
    python requests 超时与重试
    collections模块之defaultdict()与namedtuple()方法简单介绍
    setdefault函数的用法及理解
    python并发编程之IO模型 同步 异步 阻塞 非阻塞
    django+uWSGI+nginx的工作原理流程与部署过程
    Nginx静态服务配置---详解root和alias指令
  • 原文地址:https://www.cnblogs.com/yangwen0228/p/6242336.html
Copyright © 2011-2022 走看看