博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
134. Gas Station java solutions
阅读量:4344 次
发布时间:2019-06-07

本文共 1094 字,大约阅读时间需要 3 分钟。

There are N gas stations along a circular route, where the amount of gas at station i is 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 public class Solution { 2     public int canCompleteCircuit(int[] gas, int[] cost) { 3         if(gas.length == 0 || cost.length == 0 || gas.length != cost.length) return -1; 4         int total = 0,sum = 0,ans = 0; 5         for(int i = 0; i < gas.length; i++){ 6             total += (gas[i] - cost[i]); 7             if(sum < 0){ 8                 sum = gas[i] - cost[i]; 9                 ans = i;10             }else{11                 sum += (gas[i] - cost[i]);12             }13         }14         return total >= 0 ? ans:-1; 15     }16 }

 

参考思路:

http://www.cnblogs.com/felixfang/p/3814463.html

转载于:https://www.cnblogs.com/guoguolan/p/5638626.html

你可能感兴趣的文章
C#多线程实践——线程同步
查看>>
数组常用的方法filter、map、forEach、every、some
查看>>
个人项目3
查看>>
[转]编程语言与宗教
查看>>
gVIM 简洁配置 in Windows
查看>>
利用字符串通过放射执行对应的方法
查看>>
转文:ASP.NET运行机制原理
查看>>
MongoDB入门二
查看>>
XXE漏洞
查看>>
《java练习题》习题集一
查看>>
Xml中SelectSingleNode方法中的xpath用法[转]
查看>>
昨夜寒雪
查看>>
[转]Windows Shell 编程 第十三章 【来源:http://blog.csdn.net/wangqiulin123456/article/details/7988004】...
查看>>
缓存之数据库缓存依赖
查看>>
在iOS项目中,这样才能完美的修改项目名称
查看>>
jupyter && ipython notebook简介
查看>>
ECMAScript 6 入门——ES6 声明变量的六种方法
查看>>
冲刺第九天
查看>>
关于mysql的sql语句符号问题
查看>>
python网络爬虫--BeautifulSoup提取猫眼TOP100电影
查看>>