leetcode-Gas Station
来源:互联网 发布:齿轮参数计算软件 编辑:程序博客网 时间:2024/06/10 21:34
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.
思路:首先比较gas数组的和与cost数组的和,如果gas数组的和较小,说明不能够走一圈,否则进一步计算开始的index。
开始的index的特点:从index之后,gas[i]-cost[i]的和要么递增,要么大于等于0.(要点在于注意到其特点)
用变量sum存储其和,如果和sum递增或者大于等于0,并且开始index==-1,则更新index=i;否则,更新index=-1;
代码:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int totalGas=0;
int totalCost=0;
int sizeOfGas=gas.size();
int sizeOfCost=sizeOfGas;
for(int i=0; i<sizeOfGas; ++i)
{
totalGas+=gas[i];
}
for(int i=0; i<sizeOfCost; ++i)
{
totalCost+=cost[i];
}
if(totalGas < totalCost)
{
return -1;
}
else
{
int sum=gas[0]-cost[0];
int indexOfStart=sum>=0?0:-1;
for(int i=1; i<sizeOfGas; ++i)
{
if((sum+gas[i]-cost[i])>=0 || (sum+gas[i]-cost[i])>=sum)
{
sum+=gas[i]-cost[i];
if(indexOfStart == -1)
{
indexOfStart=i;
}
}
else
{
sum+=gas[i]-cost[i];
indexOfStart=-1;
}
}
return indexOfStart;
}
}
另一个较好理解的思路:
记录最后一个gas[i]-cost[i]加起来小于零的索引,然后返回这个索引+1就是答案了。
int canCompleteCircuit(vector<int> &gas, vector<int> &cost){int sum = 0;int total = 0;int j = -1;for(int i = 0; i < gas.size() ; ++i){sum += gas[i]-cost[i];total += gas[i]-cost[i];if(sum < 0){j=i; sum = 0;}}if(total<0) return -1;else return j+1;}
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- Android基础&进阶
- 第一周工作报告
- 种类数,方案划分,01背包
- C++模版基于包含模型之外的显示实例化
- 计算机网络学习心得(三)----物理层(2)
- leetcode-Gas Station
- hdu 2554 N对数的排列问题(数论:难题...但是可以蒙对)
- java中关键字volatile的作用
- 设计模式 之 单例
- uva-401 回文词
- <<Oracle Applications DBA 基础(第二期)>>Week 01 exercise
- File类中的list和listFiles方法
- hadoop 出现FATAL conf.Configuration: error parsing conf file,异常
- vertex normals 顶点向量