Gas Station (leetcode)

来源:互联网 发布:成都数控编程学徒招聘 编辑:程序博客网 时间:2024/05/29 15:18

题目:

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;}


0 0