zoukankan      html  css  js  c++  java
  • [leetcode] 134. Gas Station 解题报告(转)

    题目链接: https://leetcode.com/problems/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.

    思路: 累加在每个位置的left += gas[i] - cost[i], 就是在每个位置剩余的油量, 如果left一直大于0, 就可以一直走下取. 如果left小于0了, 那么就从下一个位置重新开始计数, 并且将之前欠下的多少记录下来, 如果最终遍历完数组剩下的燃料足以弥补之前不够的, 那么就可以到达, 并返回最后一次开始的位置.否则就返回-1.

    证明这种方法的正确性: 

    1. 如果从头开始, 每次累计剩下的油量都为整数, 那么没有问题, 他可以从头开到结束.

    2. 如果到中间的某个位置, 剩余的油量为负了, 那么说明之前累积剩下的油量不够从这一站到下一站了. 那么就从下一站从新开始计数. 为什么是下一站, 而不是之前的某站呢? 因为第一站剩余的油量肯定是大于等于0的, 然而到当前一站油量变负了, 说明从第一站之后开始的话到当前油量只会更少而不会增加. 也就是说从第一站之后, 当前站之前的某站出发到当前站剩余的油量是不可能大于0的. 所以只能从下一站重新出发开始计算从下一站开始剩余的油量, 并且把之前欠下的油量也累加起来, 看到最后剩余的油量是不是大于欠下的油量.

    代码如下:

    class Solution {
    public:
        int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
            int start = 0, lack = 0, left = 0;
            for(int i = 0; i < gas.size(); i++)
            {
                left += gas[i] - cost[i];
                if(left < 0)
                {
                    start = i+1;
                    lack += left;
                    left = 0;
                }
            }
            return left+lack>=0?start:-1;
        }
    };


    ————————————————
    版权声明:本文为CSDN博主「小榕流光」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq508618087/article/details/50990076

  • 相关阅读:
    鼠标事件
    表单事件
    打印20行10列的星形矩形
    打印nn乘法表
    小芳的妈妈每天给她2.5元钱,她都会存起来,但是,每当这一天是存钱的第5天或者5的倍数的话,她都会花去6元钱,请问,经过多少天,小芳才可以存到100元钱。
    我国最高山峰是珠穆朗玛峰:8848m,我现在有一张足够大的纸张,厚度为:0.01m。请问,我折叠多少次,就可以保证厚度不低于珠穆朗玛峰的高度?
    匿名函数
    冒泡排序
    session --中间件
    对cookie-parser的理解(签名、加密)
  • 原文地址:https://www.cnblogs.com/zl1991/p/13259346.html
Copyright © 2011-2022 走看看