国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

Leetcode 134. Gas Station

2019-11-11 07:42:05
字體:
來源:轉載
供稿:網友

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.

s思路: 1. n個加油站。簡單粗暴的方法一定是:每個加油站為起點,然后遍歷一圈,那么復雜度就是o(n^2)。顯然,這道題不是讓我們給出這樣的答案! 2. 復雜度至少應該是o(nlgn),最好的是o(n)。 3. 想了半天,剛開始是想從左往右遍歷,在每個位置處gas[i]-cost[i]得到剩余的油,如果為負值,說明需要從左邊挪一些油;為正值,則說明這個汽油站可以為后面的汽油站貢獻一些油。換一種說法:油的轉移有方向性,只允許從左邊往右邊轉移。這樣的題,油的轉移從左往右,那么我們從右往左遍歷的話,遇到負值,我們知道肯定由前面轉移過來,所以把這個負值累加到前面去,如果在某個位置的累加值大于0,則說明從這個位置其可以保證后面的都順利到達,但是這個站前面的還不一定,所以,需要繼續(xù)往前累加,找到最大的累加值的站肯定就是可以作為起始點了!

class Solution {public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { // int mxsum=0,sum=0,pos=0; for(int i=cost.size()-1;i>=0;i--){ sum+=gas[i]-cost[i]; if(sum>mxsum){ pos=i; mxsum=sum; } } return sum>=0?pos:-1; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 交口县| 通化县| 喀喇沁旗| 邓州市| 灵寿县| 普格县| 梨树县| 金阳县| 南阳市| 宜良县| 华池县| 桃园县| 余庆县| 永兴县| 贡觉县| 四子王旗| 莒南县| 玛多县| 龙门县| 宜春市| 南开区| 邵阳县| 维西| 商水县| 清水县| 新沂市| 尼木县| 阿拉尔市| 政和县| 沙雅县| 德钦县| 绥宁县| 永川市| 德格县| 阿拉善右旗| 中西区| 仙桃市| 营口市| 崇仁县| 舒城县| 耒阳市|