• 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;
            
        }
    };
  • 相关阅读:
    python——数据库操作
    【笔试】T实习生2014 总结
    【JS】Intermediate6:jQuery
    【JS】Intermediate5:Scope
    【JS】Intermediate4:JSON
    【JS】Intermediate3:AJAX
    【JS】Intermediate2:Events and Callbacks
    【JS】Intermediate1:The DOM
    【JS】Beginner9:Arrays
    【JS】Beginner8:Objects
  • 原文地址:https://www.cnblogs.com/graph/p/3352042.html
Copyright © 2020-2023  润新知