zoukankan      html  css  js  c++  java
  • lintcode-187-加油站

    187-加油站

    在一条环路上有 N 个加油站,其中第 i 个加油站有汽油gas[i],并且从第_i_个加油站前往第_i_+1个加油站需要消耗汽油cost[i]。
    你有一辆油箱容量无限大的汽车,现在要从某一个加油站出发绕环路一周,一开始油箱为空。
    求可环绕环路一周时出发的加油站的编号,若不存在环绕一周的方案,则返回-1。

    注意事项

    数据保证答案唯一。

    样例

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

    挑战

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

    标签

    贪心

    思路

    从头遍历,若当汽油量小于消耗量,则从下一个站点开始,遍历结束后,若总汽油量大于总消耗量,则一定存在解,故无需二次遍历

    code

    class Solution {
    public:
        /**
         * @param gas: a vector of integers
         * @param cost: a vector of integers
         * @return: an integer 
         */
        int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
            // write your code here
            int size = gas.size();
            if (size <= 0) {
                return 0;
            }
            int curGas = 0, start = 0, totalGas = 0, totalCost = 0;
            for (int i = 0; i < size; i++) {
                curGas += gas[i];
                curGas -= cost[i];
    
                totalGas += gas[i];
                totalCost += cost[i];
    
                if (curGas < 0) {
                    start = i + 1;
                    curGas = 0;
                }
            }
            return totalGas >= totalCost ? start : -1;
        }
    };
    
  • 相关阅读:
    mysql学习【第4篇】:数据库之数据类型
    mysql学习【第3篇】:数据库之增删改查操作
    mysql学习【第2篇】:基本操作和存储引擎
    mysql学习【第1篇】:数据库安装
    模块
    面向对象 之 反射 内置方法
    面向对象 的属性 类方法 静态方法
    python day
    day 18 面向对象的 继承
    python day
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7290764.html
Copyright © 2011-2022 走看看