leetcode之Gas Station

来源:互联网 发布:mac photoshop快捷键 编辑:程序博客网 时间:2024/06/10 19:28

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.

这道题的代码实现并不难,关键是对思路的理解。关于思路,很多博客都说明了其中的两点,但我个人感觉还需要加上第三点才更有说服性。

一、从前往后遍历一遍,如果总消耗小于总供给,则不存在这样的一条路线,否则,存在,而且由题目可知存在且唯一。

二、从前往后遍历,如果A不能到达B(B是以A为起点第一个不能到达的地点),那么以A到B之间的所有点为起点都不能到达B,此时只需以B为起点重新判断。

三、假设循环路径为A、B、C、D、E、F,如果存在E——F——A,那么从E出发到达A时所剩的汽油一定不比从F出发到达A时所剩的汽油少,而继续往下走时,A到E的消耗比A到F的消耗还要少,所以如果存在唯一解的话起点只可能是E而不可能是E之后的点。

class Solution {public:    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {int sum = 0,total = 0,index = 0;for(int i = 0; i < gas.size(); i++){sum += gas[i] - cost[i];total +=gas[i] - cost[i];if(sum < 0){    index = i + 1;sum = 0;}}if(total < 0)return -1;return index;    }};

补充:借鉴循环连续最大子段和的思路,此题可以通过将数据连续存储两遍而将问题简化为非循环问题,这种思路也更加容易理解。

int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {int len = gas.size();vector<int>v(2*len);for(int i = 0; i < len; i++){    v[i] = gas[i] - cost[i];v[i + len] = v[i];}int sum = 0, index = 0,count = 0;for(int i = 0; i < 2*len; i++){sum +=v[i];count++;if(sum < 0){    sum = 0;index = i + 1;count = 0;}if(count == len){    return index;}}return -1;}




0 0
原创粉丝点击