Algorithms—134.Gas Station
2015-06-26 14:19
567 查看
思路:每个加油站提供的油减去下一段路上耗费的油,生成新的数组。循环数组长度2倍的量,找出其中一段长度为数组长且每部的剩余油量都不小于0的;
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int[] n = new int[gas.length];
for (int i = 0; i < n.length; i++) {
n[i] = gas[i] - cost[i];
}
int sum = 0;
int begin = 0;
int truebegin=0;
for (int i = 0; i < n.length*2; i++) {
sum += n[i%n.length];
while (sum < 0) {
sum -= n[truebegin];
begin++;
truebegin=begin%n.length;
}
if (i-begin>=n.length) {
return truebegin;
}
}
return -1;
}
}
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int[] n = new int[gas.length];
for (int i = 0; i < n.length; i++) {
n[i] = gas[i] - cost[i];
}
int sum = 0;
int begin = 0;
int truebegin=0;
for (int i = 0; i < n.length*2; i++) {
sum += n[i%n.length];
while (sum < 0) {
sum -= n[truebegin];
begin++;
truebegin=begin%n.length;
}
if (i-begin>=n.length) {
return truebegin;
}
}
return -1;
}
}
相关文章推荐
- MeteoInfoLab脚本示例:inpolygon
- 韩团god朴俊亨迎娶小13岁空姐 成员唱祝歌
- Algorithms—125.Valid Palindrome
- Algorithm --> 二进制中1的个数
- Google Guava官方教程(中文版)
- Algorithms—119.Pascal's Triangle II
- Go语言用堆排序的方法进行一千万个int随机数排序.
- Algorithms—118.Pascal's Triangle
- VIEWGOOD(远古)企业培训考核提升系统解决方案
- poj 1179 Polygon
- Django 后台表单标签的自定义
- Django model字段类型清单
- Django模块笔记【一】
- 求LR(0)文法的规范族集和ACTION表、GOTO表的构造算法
- 北大百炼1003 Hangover 题解
- TEA -- Tiny Encryption Algorithm
- Algorithm --> n位数去掉k位后找最小数
- Algorithm --> 顺序打印矩阵
- Google推荐的图片加载库Glide介绍
- Google Chrome 应用商店上传扩展程序