多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > php教程 > 【Leetcode】Gas Station

【Leetcode】Gas Station

來源:程序員人生   發布時間:2016-06-25 16:11:12 閱讀次數:2501次

題目鏈接:https://leetcode.com/problems/gas-station/
題目:

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 ⑴.

Note:
The solution is guaranteed to be unique.

思路:

看了tag發現是貪心,想起老師上課說貪心實現起來是最簡單的,最難的是證明貪心策略的正確性。這里主要為了AC,多嘗試幾次可能的策略懶得證明了(寶寶TM不會證明?。。。:茏匀幌氲降牟呗杂校?、從gas最多的station開始 2、從cost最少的station開始 3、從剩余(gas-cost)最少的開始。

嘗試了幾次發現第2種是對的,但要注意如果有多個站點cost相同,要判斷這些站點是不是能完成環圈旅行。

算法:

public int canCompleteCircuit(int[] gas, int[] cost) { int index = 0; for (int i = 1; i < cost.length; i++) { if (cost[i]<cost[index]) { index = i; } } for(int i=0;i<cost.length;i++){ if(cost[i]==cost[index]){ if(isValid(cost, gas, i)!=⑴){ return i; } } } return ⑴; } public int isValid(int[]cost,int[] gas,int index){ int tankGas = 0; for(int i=index;i<gas.length;i++){ tankGas+=gas[i]-cost[i]; if(tankGas<0){ return ⑴; } } for(int i=0;i<index;i++){ tankGas+=gas[i]-cost[i]; if(tankGas<0){ return ⑴; } } return index; }


生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 性欧美高清videosex | 91精品福利一区二区 | 亚洲欧美一区二区三区综合 | 羞羞免费网页登界面入口 | 日一区二区三区 | 黄色a网站 | 秋霞午夜鲁丝片午夜精品久 | 亚洲免费网站 | 国产九色在线 | 国产综合亚洲欧美日韩一区二区 | 欧美在线播放成人免费 | 大片毛片| 亚洲伊人成人 | 亚洲日韩天堂 | 欧美在线看欧美视频免费网站 | 亚洲性xx | 久爱免费观看在线精品 | 97碰碰碰免费公开在线视频 | 日日撸夜夜操 | 亚洲精品一区二区久久 | 91精品91 | 国产综合在线观看视频 | 日韩欧美一区二区中文字幕 | 欧美巨大另类极品videosbest | 噜噜噜噜噜视频在线观看 | 伊人亚洲影院 | 又粗又大又爽 真人一级毛片 | 亚洲成人国产精品 | 亚洲视频在线观看网站 | 亚洲欧美在线精品 | 欧美1069| 国产xxxxx在线观看 | 视频在线观看免费播放www | 亚洲人网站 | 国产成人高清 | 最新69成人精品毛片 | 综合久久久久久久 | 纯欧美一级毛片_免费 | 日本一区二区三 | 另类校园春色 | 国产欧美一区二区成人影院 |