标签:0134 tank int gas Gas start Station total cost
1. 题目描述
2. Solution 1
1、思路分析
以gas=[1,2,3,4,5], cost=[3,4,5,1,2]为例
gas: 1 2 3 4 5
cost: 3 4 5 1 2
tank: -2 -2 -2 3 3
Step 1: 先分析是否有解。对上面的tank求和为total=0,当total>=0时有解。
Step 2: 若无解直接返回-1;在有解的情况下,分析找出起点start。第一个tank>=0的下标即为起点。
2、代码实现
package Q0199.Q0134GasStation;
/*
1> If car starts at A and can not reach B. Any station between A and B
can not reach B.(B is the first station that A can not reach.)
2> If the total number of gas is bigger than the total number of cost. There must be a solution.
*/
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = 0, total = 0, tank = 0;
// if car fails at start, record the next station
for (int i = 0; i < gas.length; i++)
if ((tank = tank + gas[i] - cost[i]) < 0) {
start = i + 1;
total += tank;
tank = 0;
}
return (total + tank < 0) ? -1 : start;
}
}
/*
If you are confused,(like I was before),try think about it with two passes. Use the first pass to determine if we
have a solution(property 2 above). Then use the second pass to find out the start position(use property 1).
After you are comfortable with 2 passes, you can absolutely modify it into one pass solution.
public int canCompleteCircuit(int[] gas, int[] cost) {
//determine if we have a solution
int total = 0;
for (int i = 0; i < gas.length; i++) {
total += gas[i] - cost[i];
}
if (total < 0) {
return -1;
}
// find out where to start
int tank = 0;
int start = 0;
for (int i = 0; i < gas.length;i++) {
tank += gas[i] - cost[i];
if (tank < 0) {
start = i + 1;
tank = 0;
}
}
return start;
}
*/
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
标签:0134,tank,int,gas,Gas,start,Station,total,cost 来源: https://www.cnblogs.com/junstat/p/16294353.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。