[Leetcode] Gas station @ Python

Source: Internet
Author: User

Original title address: https://oj.leetcode.com/problems/gas-station/

Test instructions

There was N gas stations along a circular route, where the amount of gas at Station I was gas[i] .

You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i] I to its next station (i+ 1). You begin the journey with a 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.

Problem-solving ideas: This problem is also very tricky, I think it is difficult to think out. If sum (gas) <sum, then there must be no solution. Saving is to walk the end of a station mailbox remaining oil, if added gas[i] also can't go to the next station, then continue to set the next station as the starting point, and then check, is not very clever?

Code: Time Complexity O (n), Space complexity O (1)

classSolution:#@param gas, a list of integers    #@param cost, a list of integers    #@return An integer    defCancompletecircuit (self, gas, cost):ifSUM (GAS) < sum (cost):return-1StartIndex=0 Saving=0 forIinchRange (len):ifGas[i] + Saving <Cost[i]: StartIndex= i + 1Saving=0Else: Saving+ = Gas[i]-Cost[i]returnStartIndex

[Leetcode] Gas station @ Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.