Leetcode:Gas Station
来源:互联网 发布:淘宝刷单改价格安全吗 编辑:程序博客网 时间:2024/06/06 02:00
URL
https://leetcode.com/problems/gas-station/description/
描述
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.
代码
class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int len = gas.length; int[] diff = new int[len]; for(int i=0;i<len;i++){ diff[i] = gas[i] - cost[i]; } int sum = diff[0]; int begin = 0,end = 0; for(int i=1;i<len;i++){ if(sum>=0){ end++; sum+=diff[end]; }else { begin--; if(begin<0) begin+=len; sum+=diff[begin]; } } return sum<0?-1:begin; }}
阅读全文
0 0
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- Web前端开发精品课HTML CSS JavaScript基础教程第五章课后编程题答案
- 做AI必须要知道的十种深度学习方法
- Google 公开 AI 发展三大方向,直言一切才刚刚开始
- 人工智能“自学”做翻译
- 进程管理API之get_pid_task
- Leetcode:Gas Station
- 你真的需要掌握多种编程语言吗?
- 有激情的程序员,其实都有病
- 编程是枯燥的,除非……
- 只有程序员了解的9个真相
- 微信小程序授权获取用户详细信息openid的实例详解
- 来自程序员老婆的感慨
- 为什么不能和程序媛谈恋爱?
- 老程序员应该记住的 5 件事