加油站

加油站

解题思路:先计算从每一个站点的油量与前往下一个站点的油量之间的差, 判断是否可以从改点通往其他站点。

再对每一个有可能的站点,计算环路的耗油量,如果跑完全程耗油量不小于0,则能行驶一周。

	public int canCompleteCircuit(int[] gas, int[] cost) 
	{
		int[] costGas = new int[gas.length];
		int sum = 0;
		int N = gas.length; // 加油站的数量
		int j = 0;
		
		for (int i=0; i<gas.length; i++)
		{ 
			costGas[i] = gas[i] - cost[i];
			sum += costGas[i];
		}
		
		System.out.println(Arrays.toString(costGas));
		
		// 无法返程
		if (sum < 0)
			return -1;
		
		for (int i=0; i<gas.length; i++)
		{
			// 寻找第一个不小于0加油站
			if (costGas[i] < 0)
				continue;
			
			N--; 
			sum = costGas[i];
			j = (i + 1) % gas.length; // 小技巧s
			while (N != 0)
			{
				sum += costGas[j];
				if (sum < 0) // 无法返程
					break;
				j = (++j) % gas.length;
				N--;
			}
			
			if (N == 0)
				return j;
			N = gas.length;
		}
		
		return -1;
	}