Leetcode: Gas Station

Source: Internet
Author: User

There areNGas stations along a circular route, where the amount of gas at StationIIsGas [I].

You have a car with an unlimited gas tank and it costsCost [I]Of gas to travel from StationITo its next station (I+ 1). You begin the journey with an 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.

Using Gas-cost to construct an array left, left [I] represents the amount of gas remaining after the I Station reaches the next stop;

Note: 1. remember to take the POs modulo and pull it back from beyond the position; 2. according to the aggregation analysis, the time complexity is O (n), because after a scan, you can determine the start position, and then append another N scans, so it is mostly 2n time. The Code is as follows:

Class solution {public: int cancompletecircuit (vector <int> & gas, vector <int> & cost) {int M = gas. size (); int COUNT = 0, sum = 0, Pos = 0, start = 0; vector <int> left; For (INT I = 0; I <m; I ++) left. push_back (gas [I]-cost [I]); For (INT I = 0; I <m; I ++) sum + = left [I]; if (sum <0) Return-1; sum = 0; while (count <m) {// use count to record the number of traveled sites sum + = left [POS]; pos = ++ POS % m; // modulo the POs value out of the range to 0, M % m = 0 both m + 1 POs and 0 if (sum <0) {sum = 0; Count = 0; Start = Pos ;} else {count ++ ;}} return start ;}};


Leetcode: Gas Station

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.