【Leetcode】Gas Station

来源:互联网 发布:安卓版打谱软件 编辑:程序博客网 时间:2024/06/15 08:55

<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);"></span>

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

You have a car with an unlimited gas tank and it costs cost[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.


我一开始想的有点简单:1)如果gas总和小于cost总和,那么肯定不行,但是如果gas>=cost,那么一定可以find way out

2)如果大于的话,那么我们岂不是找到最大的gas补给站就好了?最大的要不行,别的肯定不行了

于是我写了这么一段:

public int canCompleteCircuit(int[] gas, int[] cost){int ans=-1;//如果gas小于cost,那肯定到不了,否则是一定能if(stats(gas)<stats(cost)){return ans;}ans = maxNum(gas);return ans;}//看这一圈有多少gas或costpublic static int  stats(int[] input){int res=0;for(int i=0;i<input.length;i++){res+=input[i];}return res;}//看这个数组里面谁最多的下标public static int maxNum(int[] input){int max=0;if(input==null||input.length==0)return -1;for(int i=0;i<input.length;i++){if(input[i]>max)max = i;}return max;}

后来发现没过,因为没有考虑这种情况:尽管一开始是5(最多的),但是它要走的下面的cost也是5,紧接着的gas不如cost的多然后就没戏了。所以我们要换一个思路,我们把一圈的gas-cost加起来,从某一个点开始会“扭亏为盈”,从此gas不会小于cost,那个转折点其实就是我们要找的开始点,因为从那个点开始的话是永远不会“入不敷出”的。所以我们就记录下最后一个sum<0的点,然后把这个点+1即可,最后,由于是一个圈,所以不要忘了是(index+)%总数

public int canCompleteCircuit(int[] gas, int[] cost){int ans=-1;int sum=0;int total=0;if(stats(gas)<stats(cost))return ans;for(int i=0;i<gas.length;i++){sum += gas[i]-cost[i];total += gas[i]-cost[i];if(sum<0){ans=i;sum=0;}}if(total<0)return -1;else return (ans+1)%gas.length;}//看这一圈有多少gas或costpublic static int  stats(int[] input){int res=0;for(int i=0;i<input.length;i++){res+=input[i];}return res;}

最后跑通了~

0 0