leetcode:Gas Station
来源:互联网 发布:五轴加工中心编程软件 编辑:程序博客网 时间:2024/04/30 11:45
题目:https://oj.leetcode.com/problems/gas-station/
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.
最简单的想法当然是暴力遍历,如果能走到下一个加油站就继续不行就换一个开始结点进行遍历。。。但是想着就算这个算法能够AC也没啥技术含量,没什么意思。所以还是上网看了一下别人的解题报告,果然找到了一个比较巧妙的解法。
这种解法基于一个条件:
如果以加油站i为起点,汽车能够从加油站i到达加油站i+1则gas[i] - cost[i]肯定要大于等于0。如果能够到达第i + 2个加油站,那么gas[i] - cost[i] + gas[i + 1] - cost[i + 1]肯定也要大于等于0.......所以如果从i出发到某节点是出现gas[i] - cost[i] + ...+gas[j] - cost[j] < 0则说明从加油站i不能到达加油站j,并且从j之前的任何加油站出发也不能到达加油站j(可以这样想,如果汽车能够从加油站i到加油站k,k位于i与j之间,那么说明汽车到达k之后油箱里面剩的油至少为0,如果从i不能走到j,则从k也不能走到j),所以可以直接跳过i与j之间的加油站,测试从j+1出发能不能走到最后。
所以可以定义一个数组tmp[i] = gas[i] - cost[i]。用total计算tmp数组的总和。如果total>=0,则表明汽车是能够绕一圈的,否则不能。
另外,还有一个问题困扰到我了,为什么能走到最后一个加油站,就能走一圈呢?(不是很明白==)
AC代码:
<span style="font-size: 14px;">class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int len = gas.size(); //先求数组tmp = gas[i] - cost[i] vector<int> tmp(len,0); for(int i = 0;i < len;i++){ tmp[i] = gas[i] - cost[i]; } //因为如果车能从点i到点j则必须有从i到j的tmp之和大于0 //用sum记录车能否开到结点i+1,如果sum < 0表示不行,则要从i + 1作为下次的开始结点开始走 //total用来记录车能否绕行一圈,如果total > 0表示可以 int sum = 0,total = 0,start = 0; for(int i = 0;i < len;i++){ sum += tmp[i]; total += tmp[i]; if(sum < 0){ start = i + 1; sum = 0; } } if(total < 0) return -1; else return start; }};</span>
- 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
- 基于WOSA/XFS标准的金融开发
- OC 分类
- 非递归排序
- oracle用户创建及权限设置
- vs2010配备boost编程环境
- leetcode:Gas Station
- 大话数据结构学习笔记(四)
- Android按键事件处理流程 KeyEvent
- jQuery 之ajax jsonp跨域请求学习笔记
- 手机中执行top命令
- java发送email错误(454 Authentication failed, please open smtp flag first!)
- Android中按键消息的派发过程及源码分析
- Couldn't load BaiduMapSDK_v3_1_0: findLibrary returned null
- 最常被程序员们谎称读过的计算机书籍