leetcode贪心算法:Gas Station
来源:互联网 发布:custom.js 编辑:程序博客网 时间:2024/04/30 22:44
There are N gas stations along a circular route, where the amount of gas at stationi is
gas[i]
.You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from stationi 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. The solution is guaranteed to be unique.
题目如上,核心是能不能转一圈以及起点的问题。
这道题有2个部分需要解决。第一,能不能转一圈。这个问题比较简单的办法就是将所有的gas和cost分别加起来,比较大小,若gas的和更大些那么肯定可以转一圈。第二个问题就是起点在哪里。这个稍微复杂一些。
假设i无法到达k点(i可以到达k-1),那么我们可以说任意的位于i~k的一点都无法到达k点,那么我们可以直接从k+1这个点开始继续研究起点的问题。这个思想是研究起点的关键。
代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = 0, tank = 0, total = 0; //start记录当前起点,tank记录当前gas和cost的差,total用于统计最终的gas和cost的差
for(int i = 0; i < gas.size(); i++){
tank = tank + gas[i] - cost[i];
if (tank < 0){ //即之前说的i无法到达k的情况
start = i + 1;
total += tank; //这一步将i~k的gas和cost的差计入total,减少工作量
tank = 0; //重置tank,因为起点也重置了
}
}
total += tank;
if (total >= 0){
return start;
}
else{
return -1;
}
}
};
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = 0, tank = 0, total = 0; //start记录当前起点,tank记录当前gas和cost的差,total用于统计最终的gas和cost的差
for(int i = 0; i < gas.size(); i++){
tank = tank + gas[i] - cost[i];
if (tank < 0){ //即之前说的i无法到达k的情况
start = i + 1;
total += tank; //这一步将i~k的gas和cost的差计入total,减少工作量
tank = 0; //重置tank,因为起点也重置了
}
}
total += tank;
if (total >= 0){
return start;
}
else{
return -1;
}
}
};
本题是贪心算法的一个简单应用。核心是对start的寻找,采用本题的方法而不是从第一个到最后一个点分别尝试。降低了时间复杂度。
如有不足,请读者留言赐教。
0 0
- leetcode贪心算法:Gas Station
- [leetcode][贪心] Gas Station
- leetcode---gas-station---贪心
- leetCode #134 Gas Station 贪心
- 134. Gas Station-贪心算法
- LeetCode算法题目:Gas Station
- [leetcode] 134 Gas Station(经典dp || 贪心)
- [LeetCode]Gas Station 最大子序列和,贪心
- leetcode -- Gas Station -- 跟jump game像,重点--贪心
- 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
- C#获取web.config配置文件内容
- HNOI2017退役记
- tensorflow dynamic_rnn与static_rnn使用注意
- C++学习笔记
- 关于移动开发接口的安全性
- leetcode贪心算法:Gas Station
- hdu5104——Primes Problem(素数)
- 编程基础之设计模式
- LeetCode题目:122. Best Time to Buy and Sell Stock II
- java后台接入微信
- POJ 3335-Rotating Scoreboard(计算几何-半平面交顺时针模板)
- 读书笔记-《Spring技术内幕》-计文柯(二):AOP的实现
- 我读过的最好的epoll讲解
- 倒序遍历链表