Gas Station
2016-06-21 17:37
316 查看
一道智力题,抛去n方的解法,对于下面的做法,真的得能找到规律。
当中的题眼是The solution is guaranteed to be unique.,于是
i: 5,10,4,20,7
c: 10,11,2,10,9
就不满足,因为从4,或20都可以开始。既然unique,即如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点。
参考:点击打开链接,点击打开链接
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0 || cost == null || cost.length == 0 || gas.length != cost.length) {
return -1;
}
int sum = 0, total = 0, index = 0;
for (int i = 0; i < gas.length; i++) {
sum = sum + gas[i] - cost[i];
total = total + gas[i] - cost[i];
if (sum < 0) {
sum = 0;
index = i + 1;
}
}
if (total < 0) {
return -1;
} else {
return index;
}
}
}
当中的题眼是The solution is guaranteed to be unique.,于是
i: 5,10,4,20,7
c: 10,11,2,10,9
就不满足,因为从4,或20都可以开始。既然unique,即如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点。
参考:点击打开链接,点击打开链接
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0 || cost == null || cost.length == 0 || gas.length != cost.length) {
return -1;
}
int sum = 0, total = 0, index = 0;
for (int i = 0; i < gas.length; i++) {
sum = sum + gas[i] - cost[i];
total = total + gas[i] - cost[i];
if (sum < 0) {
sum = 0;
index = i + 1;
}
}
if (total < 0) {
return -1;
} else {
return index;
}
}
}
相关文章推荐
- 核电站问题(递推)
- iOS 获取当前月份一共多少天 ,获取当前某年某月某日, 当前日期星期几
- SpringMVC使用@ResponseBody时返回json的日期格式及可能产生的问题
- Spring笔记(七)
- Javascript——流程控制语句
- android 获取栈顶activty的方法总结(兼容API 5.0)
- 关于Android适配华为等带有底部虚拟按键的解决方案
- Android studio gradle配置
- 百度开放云物接入IoT--MQTT测试
- Underscore学习(1)
- 4.【数组】
- 观察者模式(Observer)
- xmlns:baofooattrs="http://schemas.android.com/apk/res/com.XXXX"
- js 字符串首字母大写
- 支持ie8单选框与复选框自定义样式
- android 获取栈顶activty的方法总结(兼容API 5.0)
- android 获取栈顶activty的方法总结(兼容API 5.0)
- huapin
- Objective的字符串拼接 似乎没有Swift方便,但也可以制做一些较为方便的写法
- windbg加载sos.dll