gas station java_LeetCode-134. Gas Station(JAVA)加氣站問題

There are N gas stations along a circular route, where the amount of gas at stationi is gas[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是量是gas[i]。你有車有無限容量的氣罐,從加油站i到下一個加油站站點i+1,要消耗cost[i]的氣體。你開始旅程時,氣罐是空的。回到起始加油站的指數,選擇一個起點開始旅游,如果你能在周圍環形旅行一次,就返回開始的加油站索引,否則返回-1。

注意: 答案保證是唯一的。

首先先要明白:如果一個數組的總和非負,那么一定可以找到一個起始位置,從他開始繞數組一圈,累加和一直都是非負的。

如果從i出發,那么gas[i]-cost[i](dif[i])一定是大於0的,程序中有判斷。如果dif[i]+dif[i+1]+……+dif[k-1]>=0,而dif[i]+dif[i+1]+……+dif[k-1]+dif[k]<0,此時需要重新設置開始點,那么需要從I+1開始嗎?dif[i]肯定大於0,所有從i

+1開始,肯定不可能到達k點,少加了一個正數。那么需要設置開始點為K+1;

public int canCompleteCircuit(int[] gas, int[] cost) {

// 記錄訪問的起始點

int start = 0;

// 加的氣和消耗的氣的總差值(從0開始)

int total = 0;

// 從start位置開始,加的氣和消耗的氣的總差值

int sum = 0;

for (int i = 0; i < gas.length; i++) {

int dif = gas[i] - cost[i];

sum += dif;

total += dif;

// 走到i站是負數,說明走不到i站,

// 也不能選取起始站到i站中的任何一戰

if (sum < 0) {

sum = 0;

// 下一站作為起始點

start = i + 1;

}

}

return total >= 0 ? start : -1;

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值