`
haifengyulu
  • 浏览: 14833 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

Leetcode Gas Station

阅读更多

题目:http://oj.leetcode.com/problems/gas-station/

直观的想法就是枚举每个index,判断从该index开始是否能完成旅行,时间复杂度为O(n平方),代码如下:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        for(int i=0;i<gas.length;i++){
            int remain=0;
            int count=0;
            for(int j=i;count<gas.length;j=(j+1)%gas.length){
                if(remain+gas[j]<cost[j])
                    break;
                else{
                    remain=remain+gas[j]-cost[j];
                }
                count++;
            }
            if(count==gas.length){
                return i;
            }
        }
        return -1;
    }
}

 

结果必然是大数据超时了,于是根据超时case,想了一个O(n)的算法,不过感觉有点投机取巧,说服力不强,代码如下:

public class Solution{
	public int canCompleteCircuit(int[] gas, int[] cost) {
		int[] surplus = new int[gas.length];
		int total = 0;
		int min = Integer.MAX_VALUE;
		for (int i = 0; i < gas.length; i++) {
			surplus[i] = gas[i] - cost[i];
			total += surplus[i];
			if (total < min) {
				min = total;
			}
		}
		if (total < 0)
			return -1;
		if (min >= 0)
			return 0;
		for (int i = surplus.length - 1; i >= 0; i--) {
			min += surplus[i];
			if (min >= 0) {
				return i;
			}
		}
		return -1;
	}
}

 后面CSDN上看到了一种解法,感觉挺好的,转载过来http://blog.csdn.net/fytain/article/details/12191103

public int canCompleteCircuit(int[] gas, int[] cost) {
		if (gas == null) {
			return -1;
		}
		int count = gas.length;
		
		int n = 0;
		int gasInCar = 0;
		int begin = 0;
		int end = 0;
		int i = 0;
		while (n < count - 1) {
			gasInCar += gas[i] - cost[i];
			if (gasInCar >=0) {//forward
				end++;
				i=end;
			} else {
				begin--;
				if (begin < 0) {
					begin = count - 1;
				}
				i = begin;
			}
			
			n++;
		}
		
		gasInCar += gas[i] - cost[i];
		
		if (gasInCar >= 0) {
			return begin;
		} else {
			return -1;
		}
		
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics