LeetCode之加油站

题目:在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则
返回出发时加油站的编号
,否则返回 -1。
说明:
在这里插入图片描述示例:
在这里插入图片描述
在这里插入图片描述
方法一:双循环:

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
       int start=-1,n=gas.length,g=0,i=0,j,k;
       if(n==1)return gas[0]>=cost[0]?0:-1;
		while(i<n) {
			if(cost[i]<gas[i]) {
				start=i;
				j=0;g=0;
				k=start;
				while(j<=n) {
					g=(j!=n)?g+gas[k]-cost[k]:g+gas[i];
					if(g<0)break;
					k=(k+1)<n?(++k):0;
					j++;
				}
				if(j>n)return start;
			}
			i++;
		}
		if(i==n)return -1;		
		return start;
    }
}

方法二:单循环

class Solution {
  public int canCompleteCircuit(int[] gas, int[] cost) {
    int n = gas.length;

    int total_tank = 0;
    int curr_tank = 0;
    int starting_station = 0;
    for (int i = 0; i < n; ++i) {
      total_tank += gas[i] - cost[i];
      curr_tank += gas[i] - cost[i];
      // If one couldn't get here,
      if (curr_tank < 0) {
        // Pick up the next station as the starting one.
        starting_station = i + 1;
        // Start with an empty tank.
        curr_tank = 0;
      }
    }
    return total_tank >= 0 ? starting_station : -1;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值