https://leetcode.com/problems/gas-station/

https://leetcode.com/problems/gas-station/

这道题暴力的解释可以的 但是超时 

def canCompleteCircuit(gas, cost):
    length=len(gas)
    for i in range(length):
        sgas=0
        scos=0
        for j in range(length):
            if i+j<length:
                sgas=sgas+gas[i+j]
                scos=scos+cost[i+j]
            else:
                sgas=sgas+gas[j-i-1]
                scos=scos+cost[j-i-1]
            if sgas<scos:
                break
            else:
                if j==length-1:
                    return i
    return -1

后来想不到别的算法 然而有个网友给了一些可以提高效率的方法 

假设从A到P都能正常走 然而从A到P+1点发现走到半路没有油了 

那么 下次走 直接从P+1点开始做起点

从A和P+1中间的任何一点都不能顺利走到P+1 

原因在于 假设C点开始走 那么因为A能走到C 说明 A到C后邮箱里的油Lac是》=0

从A到P+1点油小于0 从C到P+1 邮箱里还少了从A到C的Lac的量的油 更不可能走到P+1点了 

class Solution:
    # @param {integer[]} gas
    # @param {integer[]} cost
    # @return {integer}
    def canCompleteCircuit(self,gas, cost):
        length=len(gas)
        list=[]
        for i in range(length):
            list.append(gas[i]-cost[i])
        start=0
        while start<length:
            sum=0
            n=0
            for j in range(length):
                sum=sum+list[(start+j)%length]
                n=n+1
                if sum<0:
                    start=start+n
                    break
                if j==length-1 and sum>=0:
                    return start
            
        return -1


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值