[Leetcode]-gas Station

Source: Internet
Author: User

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 cost[i] of the gas-to-travel from station 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.
Hide Tags:greedy
Title: Cycle a circle of the road there are gassize gas station gas[gassize], from I to i+1 stations need to consume cost[i] gas, requirements can be from any of the gas station, as long as can guarantee back to the starting point.
Idea: the greedy algorithm.
The first cycle: from gas[0] Add gas station I from 0-> gasSize-1, stand to judge whether can go to station I, over for each station after the remaining gas, over a negative description of the current station I, when found not to the current station, immediately will be the current station I as the starting point , over zeroed, and started to move forward again.
The second cycle: Of course, it is possible to walk after a circle can not be judged, because it is possible that the starting point is not gas[0], it is necessary to continue to move forward, until Gas[start], the period as long as there is no case this judgment is-1. If the last to determine whether over is greater than 0, greater than 0 will be able to, otherwise return-1.

int Cancompletecircuit (int* gas, int. gassize, int* cost, int costsize) {int i =0; Int Over= gas[0]; int start =0;if(Gassize = =1)return(gas[0] >= cost[0]) ?0: -1; for(i=1; i<gassize;i++) { Over= Over-cost[i-1];if( Over<0) {start = i; Over=0; } Over= Over+ Gas[i]; } Over= Over-cost[gassize-1]; for(i=0; i<start;i++) {if( Over<0)        {return-1; } Over= Over+ gas[i]-cost[i]; }return( Over>=0) ? Start:-1; }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[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.