134. Gas Station
2016-09-13 21:18
239 查看
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.
Note:
The solution is guaranteed to be unique.
解题思路:
1.找到一个i gas[i]>=cost[i] 作为起始点
2.从起始点i开始计算 gas[i]和cost[i]的累加和 如果gas的累加和<cost的累加和 则这个起点不符合要求
3.注意各种情况 i从中间某个位置开始,到达末尾之后需要 从0开始继续累加计算
4.不要忘记从0开始的情况 一直加到数组的最后一位都是符合要求的此时j=len 而不是len-1
贪心算法的正规解法:
1. 如果gas的累加和大于cost的累加和 那么一定有解
2.确定有解时,怎么找这个解: 从i开始可以到结尾 那么剩余的油可以到i-1位置
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.
Note:
The solution is guaranteed to be unique.
解题思路:
1.找到一个i gas[i]>=cost[i] 作为起始点
2.从起始点i开始计算 gas[i]和cost[i]的累加和 如果gas的累加和<cost的累加和 则这个起点不符合要求
3.注意各种情况 i从中间某个位置开始,到达末尾之后需要 从0开始继续累加计算
4.不要忘记从0开始的情况 一直加到数组的最后一位都是符合要求的此时j=len 而不是len-1
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int len=gas.length; int sum=0;int con=0;int i=0;int j=0; for(i=0;i<len;i++){ if(gas[i]>=cost[i]){ for( j=i;j<len;j++){ sum+=gas[j]; con+=cost[j]; if(sum<con) { sum=0; con=0; break; } } if((i==0)&&(j==len)) return 0; //j==len 不是len-1 j在上一个for循环已经++变成了len if(sum!=0){ for( j=0;j<i;j++){ sum+=gas[j]; con+=cost[j]; if(sum<con) { sum=0; con=0; break; } if(j==i-1) return i; } } } } return -1; } }
贪心算法的正规解法:
1. 如果gas的累加和大于cost的累加和 那么一定有解
2.确定有解时,怎么找这个解: 从i开始可以到结尾 那么剩余的油可以到i-1位置
这个起点将路径分为前后两段,前段总的余量为负,即油不够用,要想有解,那么后段油量应该为正,此时才可能有解,我们要做的就是找到这个分割点作为起点,然后再验证一下;反之,如果前段就为正了,那么显然可以直接选择前面的点为起点;如果整段加起来都是负的,那么无解。
public int canCompleteCircuit(int[] gas, int[] cost) { int i=0; int left=0; int beg=0; int total=0; while(i<gas.length){ left+=gas[i]-cost[i]; total+=gas[i]-cost[i];//total为了验证整个数组是否gas>cost if(left<0){ beg=i+1; left=0; } i++; } if(total>=0) return beg; else return -1; } }
相关文章推荐
- cookie 实现显示最近一次登录时间与删除cookie
- 2016 acm香港网络赛 D.Curious Cupid[莫队算法]
- Vijos P1428 贪婪格尔曼
- Xcode 7.1 is Not on Any Development Teams问题解决办法
- Codeforces 623B Array GCD(枚举情况+dp)
- HTML FileReader
- redis三种启动设置
- Java的多线程-2
- leetcode之92. Reverse Linked List II(C++读错题版本,交换一个链表中指定的两个位置上的元素)
- javascript在html中的加载顺序
- C# 托管资源和非托管资源
- (C语言)自制贪吃蛇
- HTTPS协议
- hh
- android两种日志获取log4j
- LeetCodeOJ——10. Regular Expression Matching
- Linux下SSH免密码登录
- .net面试题
- HTML学习小结之HTML标签
- 一些linux 与磁盘相关命令