标签:
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.
比较简单的题目,只要想到一个策略就好了.(貌似是贪心?)
上代码了,其实主要思想就是看下当前的汽油够不够用.
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int g=0; int c=0; int tg=0; int tc=0; int ret=0; boolean flag = false; for(int i=0;i<cost.length;i++){ g+=gas[i]; c+=cost[i]; tg+=gas[i]; tc+=cost[i]; if(gas[i]>cost[i] && !flag){ ret = i; flag = true; } if(tg<tc){ tg=0; tc=0; flag = false; } } if(c<=g) return ret; return -1; } public static void main(String[] args) { Solution s = new Solution(); int[] gas = new int[]{2}; int[] cost = new int[]{2}; System.out.println(s.canCompleteCircuit(gas, cost)); } }
标签:
原文地址:http://www.cnblogs.com/dick159/p/5187141.html