<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    IT技術小屋

    秋風秋雨,皆入我心

      BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
      38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
    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.

    首先,這個題目要明確如果gas[0] + gas[1] + ... + gas[n] >= cost[0] + cost[1] + .. + cost[n],那么這個題目一定有解。因為,根據(jù)條件移項可得:
    (gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0,由于最終結(jié)果大于等于零,因此一定可以通過加法交換律,得到一個序列,使得中間結(jié)果都為非負。因此可以將算法實現(xiàn)如下:
     1 public class GasStation {
     2     public int canCompleteCircuit(int[] gas, int[] cost) {
     3         int sum = 0, total = 0, len = gas.length, index = -1;
     4         for (int i = 0; i < len; i++) {
     5             sum += gas[i] - cost[i];
     6             total += gas[i] - cost[i];
     7             if (sum < 0) {
     8                 index = i;
     9                 sum = 0;
    10             }
    11         }
    12         return total >= 0 ? index + 1 : -1;
    13     }
    14 }
    posted on 2013-12-19 09:29 Meng Lee 閱讀(382) 評論(1)  編輯  收藏 所屬分類: Leetcode

    評論

    # re: [Leetcode] Gas Station 2014-01-25 09:56 SunnyYoona
    (gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0
    但是并不能保證每一個(gas[i] - cost[i])都大于0

    有點疑惑。。。。  回復  更多評論
      

    主站蜘蛛池模板: 成年性羞羞视频免费观看无限 | 亚洲国产成人AV在线播放| 亚洲乱码中文字幕久久孕妇黑人| 无码视频免费一区二三区| 日韩精品无码专区免费播放| 国产免费内射又粗又爽密桃视频| 一本色道久久88亚洲精品综合| 亚洲激情中文字幕| 国产成人亚洲精品狼色在线 | 亚洲av乱码一区二区三区香蕉| 亚洲综合AV在线在线播放| 永久中文字幕免费视频网站| 希望影院高清免费观看视频| 三年片在线观看免费观看大全一| 国产黄色免费观看| 白白色免费在线视频| 精品久久久久久久久亚洲偷窥女厕| 精品亚洲成A人无码成A在线观看| 91亚洲国产在人线播放午夜| 亚洲AV无码码潮喷在线观看| 亚洲日韩中文字幕在线播放| 亚洲男人的天堂一区二区| 亚洲Av无码国产情品久久| 免费国产成人高清视频网站| 国产男女猛烈无遮挡免费视频网站 | 久久免费99精品国产自在现线| 国产亚洲视频在线| MM1313亚洲国产精品| 爱爱帝国亚洲一区二区三区| 国产精品国产亚洲区艳妇糸列短篇| 亚洲中文字幕精品久久| 在线观看亚洲AV每日更新无码| 日韩亚洲国产高清免费视频| 亚洲熟女乱色一区二区三区| 亚洲精品无码高潮喷水A片软| 亚洲人成色777777精品| 精品无码专区亚洲| av成人免费电影| 精品四虎免费观看国产高清午夜| 久久国产免费一区| 精品免费人成视频app |