LeetCode_134: Gas Station

这道题目可以使用一般的DP来做,但是博主想到的方法更加直接:对于判断是否存在解,直接把数组累加,如果和非负,那么必然存在一个位置,使得从这个位置开始进行累加的所有结构都非负。在进行累加的过程中,找到累加和最小的位置,从这个位置的下一个位置开始,就可以保证在累加过程中,累加曲线的最小值最大(想象积分曲线的过程,积分的终点sum相同,一个先下降再上升,一个先上升再下降)。有点绕,多想想 :)

题目

  • Total Accepted: 84105
  • Total Submissions: 289535
  • Difficulty: Medium
  • Contributor: LeetCode

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.

代码

分析就在摘要里面了,直接上代码。

class Solution {
public:
	int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
		const int n = gas.size();
		int cum = 0, min = INT_MAX, minid = -1;
		for (int i = 0; i < n; ++i){
			int tmp = gas[i] - cost[i];
			cum += tmp;
			if (cum < min){
				min = cum;
				minid = i + 1;
			}
		}
		if (minid == n){
			minid = 0;
		}
		return (cum < 0) ? -1 : minid;
	}
};

 

发表评论