Java for Leetcode 134

Source: Internet
Author: User

accepted:39396 Total submissions:153479

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.

Problem Solving Ideas:

Because the answer is unique, you can only go in one direction (no need to consider the situation from I+1→i)

Considering the departure from I, after reaching the i+j can not go forward, then from the I+i, the maximum can only reach i+j, so the next cycle can start from i+j+1, Java implementation is as follows:

public int cancompletecircuit (int[] gas, int[] cost) {for (int i = 0; i < gas.length; i++) {int sum = gas[i]-cost[i]; int index = i, count = 0;while (sum >= 0) {if (++count = = gas.length) return index;int j = ++i% gas.length;sum + = Gas[j ]-cost[j];}} return-1;}

Java for Leetcode 134

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.