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;
        }
    };
    
  • 相关阅读:
    MicXP程序爱好者
    cnblogs上的mysql学习心得
    iwebship 购物系统 PHP lamp环境
    可以购买的网址
    模板网址
    学习ecshop 教程网址
    ecshop数据库操作函数
    yzoj1568: 数字组合 题解
    yzoj1891 最优配对问题 题解
    yzoj1985 最长公共单调上升子序列 题解
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7290764.html
Copyright © 2011-2022 走看看