LeetCode Gas Station


https://oj.leetcode.com/problems/gas-station/


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.

这实际上是一个球最长字序列和大于零的问题,gas[i]的值相当于正数,cost[i]相当于负数,他们交叉组成一个排列。


一开始我用最通俗的方法做,从i开始一直加减数看一下能不能围一圈。这个方法的复杂度是O(2N),最后超时了。



public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
		
		int n = gas.length;
		int [][]COST = new int [n][n];
		for(int i=0;i<n;i++)
		{
			COST[i][i]=0;
		}
		
		
		for(int i=0;i<n;i++)
		{
			boolean temp = true;
			for(int j=1;j<=n;j++)
			{
				COST[i][(i+j)%n]=COST[i][(i+j-1)%n]+gas[(i+j-1)%n]-cost[(i+j-1)%n];
				if(COST[i][(i+j)%n]<0)
				{
					temp = false;
					break;
				}
			}
			if(temp)
			{
				return i;
			}
			
		}
		
		return -1;
	}
}





其实这个题可以用动态规划的方法进行解答。如果从rest[I][J]表示从i到j所剩余的油量,如果为负值,那么从I到J的任何一个位置到J,rest的值都是负的。

因为这个位置之前的那些位置必须是gas>=cost才能保证到达该点。从该点到J相当有rest减去gas-cost, 是减去了一个非负值。所以rest不可能为非负的。


public class Solution {
		public int canCompleteCircuit(int[] gas, int[] cost) {
		
		int n = gas.length;
		int rest=0;
		int head = 0;
		int length = 0;
		for(int i=1;i<2*n;i++)
		{
			rest += gas[(i-1)%n]-cost[(i-1)%n];
			length++;
			if(length==n)break;
			if(rest<0)
			{
				head = i;
				rest=0;
				length = 0;
			}
		}
		if(length==n&&rest>=0&&head<n)return head;
		return -1;
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值