• [LeetCode]题解(python):134-Gas Station


    题目来源:

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


    题意分析:

      在一个圈子路线里面有N个汽油站,i站的汽油有gas[i]汽油。现在有一辆无限容量的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那么返回这个车的起点,否者返回-1.


    题目思路:

      不难发现,如果gas的总和大于或等于cost的总和,必然存在一种路线使得走完整个圈子。那么只要找到一个起点i,从这个起点出发的所有gas的和总比cost的和大就可以了。


    代码(python):

    class Solution(object):
        def canCompleteCircuit(self, gas, cost):
            """
            :type gas: List[int]
            :type cost: List[int]
            :rtype: int
            """
            begin,subsum,sum,i = 0,0,0,0
            while i < len(gas):
                sum += gas[i] - cost[i]
                subsum += gas[i] - cost[i]
                if subsum < 0:
                    subsum,begin = 0,i + 1
                i += 1
            if sum < 0:
                return -1
            else:
                return begin
    View Code
  • 相关阅读:
    P4005 小 Y 和地铁
    P1039 侦探推理
    P2766 最长不下降子序列问题
    P2312 解方程
    P2169 正则表达式
    UOJ#22. 【UR #1】外星人
    UOJ#21. 【UR #1】缩进优化
    Palindromeness CodeChef
    bzoj5392 [Lydsy1806月赛]路径统计
    997D Cycles in product
  • 原文地址:https://www.cnblogs.com/chruny/p/5354983.html
Copyright © 2020-2023  润新知