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.

解法

这道题分两步来做,第一步先确定是否能周游一圈,第二步在找从哪个加油站开始。

确定能否周游一圈

首先给出一个断言:如果gas数组元素之和大于等于cost数组元素之和,那么必然能周游一圈。证明很简单,可以这样想象下,加油站的高度为0,加油站的油高度为gas,cost代表两个加油站之间的坑深度,且油的流向为同一个方向,那么当gas之和大于等于cost之和的话,最终动态平衡后整体油面高度>=0,那么必然能周游一圈。否则不能。

从哪个加油站开始

一开始没看到题目的note,感觉可以从多个加油站开始。note提示题目有唯一解,我想如果能找到环中最大连续序列的和的话,那么就能找到其实点,但是找环中的最大连续感觉比找数组中最大连续序列和(见http://blog.csdn.net/xhu_eternalcc/article/details/24880013)要难,就直接蛮力找的:如果从某个加油站能向前遍历N步(加油站的个数),那么就是从这个加油站开始,需要进行如下优化:

det[i]=gas[i]-cost[i]

sum为从第i个加油站开始,向前遍历到某加油站时的总剩油量

1)起始加油站的det[i]>=0

2)  当从第i个加油站开始,向前step步,到达第(i+step)%N个加油站,sum<0时,这时在探测第x= i+1 至(i+step)%N个加油站能否作为开始点时,可以直接求得从加油站x到(i+step)%N 的总剩油量sum,详见代码。

代码

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int sum=0;
        int *det=new (std::nothrow)int[gas.size()];
        for(std::vector<int>::size_type i=0;i<gas.size();++i){
            det[i]=gas[i]-cost[i];
            sum+=det[i];
        }
        if(sum<0){
            delete [] det;
            return -1;
        }
        int step=0;
        for(std::vector<int>::size_type i=0;i<gas.size();++i){
            if(step>0){//i-1加油站向前走step步后总油量开始<0
                --step;
                if(det[i]<0){
                    sum-=det[i];
                    continue;
                }else if(sum<0){
                    sum-=det[i];
                    continue;
                }
            }else{
                if(det[i]<0)
                    continue;
                sum=det[i]; 
            }
            while(sum>=0&&step<gas.size()){
                ++step;
                sum+=det[(step+i)%gas.size()];
            }
            if(step==gas.size()){
                delete [] det;
                return i;
            }
            else
                sum-=det[i];
        }
    }
};





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值