Partition List @ LeetCode (Python)
Clone Graph @ LeetCode (Python)

Gas Station @ LeetCode (Python)

kitt posted @ 2014年3月15日 15:26 in LeetCode , 2432 阅读

看了网上的解法, 太巧妙了。如果sum(gas) < sum(cost)则无解, 否则必定有解。Sum < 0那一块不考虑, 因为total >= 0, 所以剩下那一块必定Sum >= 0。

class Solution:
    # @param gas, a list of integers
    # @param cost, a list of integers
    # @return an integer
    def canCompleteCircuit(self, gas, cost):
        num = len(gas)
        Sum = total = 0
        k = -1
        for i in xrange(num):
            Sum += gas[i] - cost[i]
            total += gas[i] - cost[i]
            if Sum < 0:
                k = i
                Sum = 0
        return k + 1 if total >= 0 else -1
Avatar_small
AP SSC Hindi Questio 说:
2022年9月16日 12:58

Every student of class 10 can learn Hindi easily and this is or National language, Hindi is the most important language for every student, AP SSC Hindi Question Paper and the Board of Secondary Education, Andhra Pradesh (BSEAP) class 10th of SSC students also can download the AP 10th Hindi Model Paper 2023 Pdf with Solved question paper in chapter wise for all lessons of the course as AP SSC Hindi Model Paper 2023. Every student of class 10 can learn Hindi easily and this is or National language, Hindi is the most important language for every student.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter