leetcode gas stations l汽车能够绕圈l问题

原题描述如下

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].

You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i to 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.

翻译过来的意思是

沿着环形路线 有N个加油站,其中站i的气体量是气体[i]。

你有一辆带有无限油箱的汽车,从车站i到下一站(i + 1)需要花费{i]气。您可以在其中一个加油站开始使用空罐。

如果您可以在电路周围移动一次,则返回起始加油站的索引,否则返回-1。

注意: 
解决方案保证是唯一的。

思路:汽车从该站到下一站时,假设汽车出发站点为i,则当前拥有汽油量为gas[i],出发到下一站所需汽油为cost[i],所以汽车到下一站所剩的汽油应为gas[i]-cost[i],鉴于此,我们可以维持一个剩余量汽油数组remain,remain的每一项都为gas[i]-cost[i],从而汽车能绕一圈的问题转换为在remain中,找出一个索引,使得每次加上下一项时,所得的和都大于零。依照此种思路,有如下代码实现

 

package com.ACM;

/**
 * @author zoujianglin
 * @date 2018/8/8 12:53
 */
public class OtherSolution {

    public static void main(String[] args) {
        int[] gas = new int[]{1, 2};
        int[] cost = new int[]{2, 1};
        canCompleteCircuit(gas, cost);
    }

    public static int canCompleteCircuit(int[] gas, int[] cost) {
        int[] remain = new int[gas.length];
        for (int i = 0; i < gas.length; i++) {
            remain[i] = gas[i] - cost[i];
        }
        int count = 0;//count用于记录所经历的站数
        int j;
        for (int i = 0; i < remain.length; i++) {
            int gasremain = 0; //用于记录每次累加的和
            for (j = i; ; ) {
                if (j >= remain.length) { //说明走循环数组的末尾,从0开始继续
                    j = 0;
                }
                if (count >= remain.length) { //进入此处时说明已经走完所有站数
                    break;
                }
                gasremain += remain[j]; //累加所剩余的油量
                if (gasremain < 0) { //油量小于0 不符合要求 退出
                    count = 0;//不符合要求 需要 count 需要置为零便于下次循环使用
                    break;
                }
                j++;
                count++;
            }
            if (count == remain.length) {
                return i; //满足条件返回
            }

        }

        return -1;
    }


}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值