Gas Station [leetcode] 的两种解法
2014-10-08 23:21
337 查看
由于gas总量大于cost总量时,一定可以绕所有城市一圈。
第一种解法:
假设一开始有足够的油,从位置i出发,到位置k时剩余的油量为L(i,k)。
对任意的k,L(i,k)根据i的不同,只相差常数。
我们只需要找到最小的L(0, k)对应的k,k+1为所求。
代码如下:
第二种解法:
如果L(i,k) < 0,则从i和k之间所有的位置都不能到k
所以从k+1的位置从0开始找
第一种解法:
假设一开始有足够的油,从位置i出发,到位置k时剩余的油量为L(i,k)。
对任意的k,L(i,k)根据i的不同,只相差常数。
我们只需要找到最小的L(0, k)对应的k,k+1为所求。
代码如下:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int start = 0; int curGas = 0, minGas = 0, totalGas = 0; for (int i = 0; i < gas.size(); i++) { int temp = gas[i] - cost[i]; curGas += temp; totalGas += temp; if (minGas > curGas) { start = i + 1; minGas = curGas; } } if (totalGas >= 0) return start % gas.size(); else return -1; }
第二种解法:
如果L(i,k) < 0,则从i和k之间所有的位置都不能到k
所以从k+1的位置从0开始找
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int start = 0; int curGas = 0, totalGas = 0; for (int i = 0; i < gas.size(); i++) { int temp = gas[i] - cost[i]; curGas += temp; totalGas += temp; if (curGas < 0) { start = i + 1; curGas = 0; } } if (totalGas >= 0) return start % gas.size(); else return -1; }
相关文章推荐
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
- LeetCode Gas Station 两个特性,两种方法完美解答-更新证明方法
- LeetCode Gas Station 两个特性,两种方法完美解答-更新证明方法
- leetcode题目:gas-station 使用start/end方法的个人理解
- leetcode贪心算法:Gas Station
- [leetcode] 134 Gas Station
- Leetcode——134 Gas Station
- leetcode — gas-station
- [leetcode][贪心] Gas Station
- LeetCode 134 Gas Station
- Leetcode-gas-station
- [leetcode]Gas Station
- [LeetCode] 133: Gas Station
- leetcode-Gas Station
- [LeetCode] Gas Station
- leetCode---Gas Station
- [leetcode] Gas Station
- leetcode gas station
- 【leetCode百题成就】Gas Station解题报告