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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Leetcode 134. Gas Station

2019-11-14 08:59:08
字體:
供稿:網(wǎng)友

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

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ā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 杭锦后旗| 万盛区| 长丰县| 红桥区| 册亨县| 凌海市| 太白县| 甘南县| 铜陵市| 新河县| 娱乐| 辽阳县| 顺义区| 育儿| 福海县| 广州市| 西平县| 荥阳市| 马公市| 易门县| 乾安县| 收藏| 铁岭县| 印江| 山阴县| 香港 | 乡宁县| 密山市| 朝阳市| 夹江县| 阿克| 宜春市| 襄城县| 濉溪县| 响水县| 黔南| 池州市| 桃源县| 宽甸| 瓮安县| 南宫市|