Gas Station(leetcode)
2014-11-15 09:14
302 查看
题目:
There are N gas stations along a circular route, where the amount of gas at station i is
You have a car with an unlimited gas tank and it costs
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.
题目来源:https://oj.leetcode.com/problems/gas-station/
解题思路:从gas[i]>cost[i]的汽油站开始,保证车内加的油要大于消耗的油即可,如果不满足,则从不满足的值k的下一个k+1开始接着寻找这个能满足的i,直到最后。《leetcode题解》中的代码更短,思路也更清晰。
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.
题目来源:https://oj.leetcode.com/problems/gas-station/
解题思路:从gas[i]>cost[i]的汽油站开始,保证车内加的油要大于消耗的油即可,如果不满足,则从不满足的值k的下一个k+1开始接着寻找这个能满足的i,直到最后。《leetcode题解》中的代码更短,思路也更清晰。
#include<iostream> #include<vector> using namespace std; int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { if(gas.empty()) return 0; for(int i=0;i<gas.size();i++) { if(gas[i]>=cost[i]) { int j=0,sumGas=0,sumCost=0; bool flag=true; for(j=i;j<gas.size();j++) { sumGas+=gas[j]; sumCost+=cost[j]; if(sumGas<sumCost) { i=j; flag=false; break; } } j=gas.size()-1; if(flag==true) { for(j=0;j<i;j++) { sumGas+=gas[j]; sumCost+=cost[j]; if(sumGas<sumCost) return -1; } if(i==j) return i; } } } return -1; } int main() { const int N=1; int A[]={2}; int B[]={2}; vector<int> gas(A,A+N); vector<int> cost(B,B+N); int result=canCompleteCircuit(gas,cost); system("pause"); return 0; }
相关文章推荐
- Leetcode-134-Gas Station C#
- Leetcode: Gas Station
- LeetCode:Gas Station
- leetcode Gas Station
- Leetcode_gas-station
- leetcode笔记:Gas Station
- [LeetCode] Gas Station,转化为求最大序列的解法,和更简单简单的Jump解法。
- LeetCode - Gas Station
- LeetCode——gas station
- LeetCode-----------gas-station
- leetcode :Gas Station
- 【leetCode百题成就】Gas Station解题报告
- LeetCode2.1.21(Gas Station)
- [LeetCode]Gas Station
- [LeetCode]Gas Station
- leetcode题目:gas-station 使用start/end方法的个人理解
- leetcode:Gas Station
- [leetcode]Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station