zoukankan      html  css  js  c++  java
  • 0134加油站 Marathon

    在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

    你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

    如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

    说明:

    如果题目有解,该答案即为唯一答案。
    输入数组均为非空数组,且长度相同。
    输入数组中的元素均为非负数。
    示例 1:

    输入:
    gas = [1,2,3,4,5]
    cost = [3,4,5,1,2]

    输出: 3

    解释:
    从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
    开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
    开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
    开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
    开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
    开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
    因此,3 可为起始索引。
    示例 2:

    输入:
    gas = [2,3,4]
    cost = [3,4,3]

    输出: -1

    解释:
    你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
    我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
    开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
    开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
    你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
    因此,无论怎样,你都不可能绕环路行驶一周。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/gas-station

    参考:

    python

    # 0134.加油站
    # 以下来自力扣-代码随想录
    # 链接:https://leetcode-cn.com/problems/gas-station/solution/134-jia-you-zhan-tan-xin-jing-dian-ti-mu-xiang-jie/
    
    
    class Solution:
        def canCompleteCircuit(self, gas: [int], cost: [int]) -> int:
            """
            暴力法, for循环控制遍历, while循环控制走一圈,index控制循环的index
            时间O(n^2), 空间复杂度O(n)
            :param gas:
            :param cost:
            :return:
            """
            for i in range(len(cost)):
                rest = gas[i] - cost[i] # 剩余油量
                index = (i+1) % len(cost)
                while rest > 0 and index != i: # 模拟以i为起点行驶一圈
                    rest += gas[index] - cost[index]
                    index = (index+1) % len(cost)
                # 如果以i为起点跑一圈,剩余油量>=0,返回起始位置
                if rest>=0 and index == i: return i
            return -1
    
    class Solution1:
        def canCompleteCircuit(self, gas: [int], cost: [int]) -> int:
            """
            贪心算法1:时间O(n), 空间O(1)
            直接从全局进行贪心选择,情况如下:
            情况一:如果gas的总和小于cost总和,那么无论从哪里出发,一定是跑不了一圈的
            情况二:rest[i] = gas[i]-cost[i]为一天剩下的油,
                i从0开始计算累加到最后一站,如果累加没有出现负数,说明从0出发,
                油就没有断过,那么0就是起点。
            情况三:如果累加的最小值是负数,汽车就要从非0节点出发,从后向前,
                看哪个节点能这个负数填平,能把这个负数填平的节点就是出发节点。
    
            :param gas:
            :param cost:
            :return:
            """
            curSum = 0
            min = float("INF")
            for i in range(len(gas)):
                rest = gas[i] - cost[i]
                curSum += rest
                if curSum < min:
                    min = curSum
            if curSum < 0: return -1 # 情况1
            if min >= 0: return 0 # 情况2
            # 情况3
            for i in range(len(gas)-1, -1, -1):
                rest = gas[i] - cost[i]
                min += rest
                if min >= 0: return i
            return -1
    
    class Solution2:
        def canCompleteCircuit(self, gas: [int], cost: [int]) -> int:
            """
            贪心算法2,局部最优,全局最优
            首先如果总油量减去总消耗大于等于零那么一定可以跑完一圈,
            说明 各个站点的加油站 剩油量rest[i]相加一定是大于等于零的。
            每个加油站的剩余量rest[i]为gas[i] - cost[i]。
            i从0开始累加rest[i],和记为curSum,一旦curSum小于零,
            说明[0, i]区间都不能作为起始位置,起始位置从i+1算起,再从0计算curSum
            :param gas:
            :param cost:
            :return:
            """
            curSum = 0
            totalSum = 0
            start = 0
            for i in range(len(gas)):
                curSum += gas[i] - cost[i]
                totalSum += gas[i] - cost[i]
                if curSum < 0: # 当前累加<0
                    start = i + 1 # 起始位置更新 i+1
                    curSum = 0 # curSum 从0开始
            if totalSum < 0: return -1 # 累加和小于0,说明不可能跑完一圈, 否则,返回start
            return start
    
    
    
    
    if __name__ == "__main__":
        gas = [1,2,3,4,5]
        cost = [3,4,5,1,2]
        test = Solution2()
        print(test.canCompleteCircuit(gas, cost))
    

    golang

    package greedy
    
    import (
    	"math"
    )
    
    // 暴力解法
    func canCompleteCircuit1(gas, cost []int) int {
    	var rest, index int
    	for i:=0;i<len(gas);i++ {
    		rest = gas[i] - cost[i]
    		index = (i+1) % len(cost)
    		for rest > 0 && index != i {
    			rest += gas[index] - cost[index]
    			index  = (index+1) % len(cost)
    		}
    		if rest >= 0 && index == i {
    			return i
    		}
    	}
    	return -1
    }
    
    // 贪心算法1-3-case
    func canCompleteCircuit2(gas, cost []int) int {
    	var curSum, rest int
    	min := math.MaxInt64
    	for i:=0;i<len(gas);i++ {
    		rest = gas[i] - cost[i]
    		curSum += rest
    		if curSum < min {
    			min = curSum
    		}
    	}
    	// case1, 不可能跑完圈
    	if curSum < 0 {
    		return -1
    	}
    	// case2, index=0处跑完
    	if min >= 0 {
    		return 0
    	}
    	// case3, 中间元素开始跑完圈
    	for i:=len(gas)-1;i>=0;i-- {
    		rest = gas[i] - cost[i]
    		min += rest
    		if min >= 0 {
    			return i
    		}
    	}
    	return -1
    }
    
    // 贪心算法2-遇到curSum<0的,更新start
    func canCompleteCircuit3(gas, cost []int) int {
    	var curSum, totalSum, start int
    	for i:=0;i<len(gas);i++ {
    		curSum += gas[i] - cost[i]
    		totalSum += gas[i] - cost[i]
    		if curSum < 0 {
    			start = i + 1
    			curSum = 0
    		}
    	}
    	if totalSum < 0 {return -1}
    	return start
    }
    
    
  • 相关阅读:
    windows 将常用程序添加到右键菜单中去
    用MediaPlayer播放assets中的音乐文件出现的问题
    android开发技巧
    windows下如何安装java6.0
    ubuntu下运行windows程序wine
    ubuntu系统备份与恢复
    Mongo北京大会3月3号召开!报名抢注火爆进行中!(免费)
    《人月神话》作者Frederick P. Brooks, Jr.大师论设计原本
    HTML 5:富媒体时代的Web内容新规范
    2011年3月华章新书书讯:ASP.NET本质论、Erlang编程指南、SNS网站构建
  • 原文地址:https://www.cnblogs.com/davis12/p/15611506.html
Copyright © 2011-2022 走看看