134. Gas Station
2016-04-14 08:01
337 查看
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
Solution
// if a car starts at A and fails at/before B, then any point between A and
// B cannot be a start point
// If the total number of gas is bigger than the total number of cost. There
// must be a solution.
public int canCompleteCircuit(int[] gas, int[] cost) {
int sumGas = 0;
int sumCost = 0;
int start = 0;
int tank = 0;
for (int i = 0; i < gas.length; i++) {
sumGas += gas[i];
sumCost += cost[i];
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
if (sumGas < sumCost) {
return -1;
} else {
return start;
}
}
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.
Solution
// if a car starts at A and fails at/before B, then any point between A and
// B cannot be a start point
// If the total number of gas is bigger than the total number of cost. There
// must be a solution.
public int canCompleteCircuit(int[] gas, int[] cost) {
int sumGas = 0;
int sumCost = 0;
int start = 0;
int tank = 0;
for (int i = 0; i < gas.length; i++) {
sumGas += gas[i];
sumCost += cost[i];
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
if (sumGas < sumCost) {
return -1;
} else {
return start;
}
}
相关文章推荐
- Centos配置Caffe详解
- bzoj 1187: [HNOI2007]神奇游乐园 插头dp
- 3770: 疯狂的限制 乱搞
- Android 基本控件的使用一(用户的登录界面)
- 173. Binary Search Tree Iterator
- 2016年4月14日
- Penguins DbTools数据库管理移植差分工具(EXCEL相关) ver 20160414
- HTML5_Web Workers
- JS创建新元素组与删除当前元素组
- Maven教程
- 欢迎使用CSDN-markdown编辑器
- LeetCode 281. Zigzag Iterator(之字形迭代器)
- CQOI2016 bzoj4522 密钥破解
- Cocos2D在新版Swift中常量枚举值引用代码的修改
- Cocos2D在新版Swift中常量枚举值引用代码的修改
- Cocos2D在新版Swift中常量枚举值引用代码的修改
- delegate的内存管理属性是weak还是assign
- Spark on YARN 部署
- 每日开源新闻速递(2016/4/14):Ubuntu 16.04 将同时提供 snap 软件包格式
- js渲染引擎 tempo.js