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

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

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

    IT技術(shù)小屋

    秋風秋雨,皆入我心

      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永久免费| 伊人久久亚洲综合| 久久精品国产亚洲av天美18 | 无码不卡亚洲成?人片| 亚洲AV综合色区无码一二三区 | 亚洲AV无码一区二区三区牲色 | 一级做a爰片性色毛片免费网站| 国产一级理论免费版| 免费精品视频在线| 久久影视国产亚洲| 免费看无码特级毛片| 久久国产亚洲精品无码| 免费在线看v网址| 亚洲国产精品久久久久秋霞小 | 免费高清在线影片一区| 最新亚洲人成无码网www电影| 免费一级毛片在线观看| 一级毛片a免费播放王色电影 | 亚洲啪啪综合AV一区| 无码人妻AV免费一区二区三区 | 亚洲成A∨人片天堂网无码| 精选影视免费在线 | 亚洲精品综合一二三区在线| 91av在线免费视频| 亚洲成AV人片高潮喷水| 国产亚洲精品精品国产亚洲综合| 久久99精品国产免费观看| 亚洲一卡2卡3卡4卡乱码 在线| 国产做床爱无遮挡免费视频| baoyu122.永久免费视频| 亚洲一区二区三区播放在线| 免费人成在线观看网站视频| 91香焦国产线观看看免费| 亚洲av成人无码网站…| 亚洲成人在线电影| 国产传媒在线观看视频免费观看 | 美女视频黄免费亚洲| 国产亚洲精品美女久久久久久下载| 亚洲色欲久久久综合网东京热| 成人免费福利视频|