<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或cost public 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; }
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或cost public static int stats(int[] input){ int res=0; for(int i=0;i<input.length;i++){ res+=input[i]; } return res; }
最后跑通了~
原文地址:http://blog.csdn.net/qbt4juik/article/details/45016365