[Leetcode] Gas station

Source: Internet
Author: User

New Year, everyone Happy New Year ~ ~ Because of the new year, so seldom do the problem recently, today finally have time to play code 134. Gas station.

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.

A simple question, just think of a strategy is good. (seemingly greedy?)

On the code, in fact, the main idea is to see the current petrol enough to use.

 Public classSolution { Public intCancompletecircuit (int[] Gas,int[] cost) {        intG=0; intC=0; intTg=0; intTc=0; intRet=0; BooleanFlag =false;  for(inti=0;i<cost.length;i++) {g+=Gas[i]; C+=Cost[i]; TG+=Gas[i]; TC+=Cost[i]; if(Gas[i]>cost[i] &&!flag) {ret=i; Flag=true; }            if(tg<TC) {TG=0; TC=0; Flag=false; }        }        if(c<=g)returnret; return-1; }     Public Static voidMain (string[] args) {solution S=Newsolution (); int[] gas =New int[]{2}; int[] Cost =New int[]{2};    System.out.println (S.cancompletecircuit (gas)); }}

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