Leetcode: 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.

 

思路

1. 最朴素的解法是对每一个起点测试, 复杂度为 o(n^2), 太慢了

2. 一个改进的方法. 依然对每一个起点测试, 但是下一个节点可以利用前一个节点的结果. 复杂度为 o(n), 实现较复杂. 并且, 超时了

3. (2) 的做法还可以作改进. 改进基于一个 Observation, 假设起点是 i, 走到 j 时, 发现剩下的油不够了. (2) 的做法是从 i+1 开始, 再走. 但是, 从 i+1 ->j 之间的节点, 肯定都之恩能够走到 j. 原因是 gas[i]-cost[i] >= 0, 也就是说经过 i 节点, 对我们来讲是一定有益的, 所以放弃 i 不会对全局有好的影响. 所以下一个起点应该是 j+1

4. 找到起点后, 需要再验证一下

 

代码

class Solution {

public:

    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {

        // Note: The Solution object is instantiated only once and is reused by each test case.

        int head = 0, tail = 0;

		int stationPassed = 1, gasLeft = 0;

		head = 0;

		for(int i = 0; i < gas.size(); i ++) {

			gasLeft = gas[i] + gasLeft - cost[i];

			if(gasLeft < 0) {

				gasLeft = 0;

				head = i+1;

			}

		}



		if(head >=gas.size())

			return -1;

		int res = head;

		// check start 

		while(stationPassed <= gas.size() && gasLeft >= 0) {

			gasLeft = gasLeft + gas[head] - cost[head];

			head = (head+1)%gas.size();

			stationPassed ++;

		}

		if(gasLeft < 0 )

			return -1;



		return res;

	}

};

  

你可能感兴趣的:(LeetCode)