zoukankan      html  css  js  c++  java
  • 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;
            
        }
    };
  • 相关阅读:
    java回顾之多线程
    java回顾之异常
    模拟斗地主和冒泡排序
    java回顾之Map
    java回顾之集合List
    java回顾之树
    java回顾之单列集合、泛型、数据结构
    java回顾之类API再体验之引用类型小结
    java回顾之API初体验
    函数之 闭包函数 和 装饰器
  • 原文地址:https://www.cnblogs.com/graph/p/3352042.html
Copyright © 2011-2022 走看看