• LeetCode _ 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.
    

    思路: 类似KMP不回朔的思想。start表示开始的点,sum表示当前汽车的油量。当汽车到达汽油站i时如果不能到达下一站,则更新start直到可以使汽车能够从当前节点到达下一站,如果不存在,则把start设置为下一站。

    class Solution {
    public:
        int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
           int len = gas.size();
           if(cost.size() != len) return -1;
           vector<int> flag(len*2, 0);
           for(int i = 0; i< len; i++)
                flag[i] = gas[i] - cost[i];
           for(int i = len ; i< len *2; ++i)
                flag[i] = flag[i-len];
        
           int start = 0 , sum = 0;         
           for(int i = 0; i< len + start && start < len; )
            {
                sum += flag[i] ;
                if(sum >= 0){
                    ++i;
                    continue;
                } 
                while(sum< 0 && start < i){
                    sum -= flag[start];
                    ++start;
                }
                i++;
                if(sum < 0){
                    sum = 0;
                    start = i;
                }
                
            }
            if(start <len)
             return start;
            return -1;
            
        }
    };
  • 相关阅读:
    《人月神话》阅读笔记02
    学习进度条-4
    课堂作业3
    MySql 8.0及对应驱动包匹配注意点
    关于Ubuntu中Could not get lock /var/lib/dpkg/lock解决方案
    STM32之ADC配置,ADC_Mode模式理解
    STM32串口中断的方式发送
    RTC 与RCC 之间的关系
    stm32 MDK5软件仿真之查看io口输出
    STM32 PWM学习
  • 原文地址:https://www.cnblogs.com/graph/p/3352042.html
Copyright © 2020-2023  润新知