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

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

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

    IT技術(shù)小屋

    秋風(fēng)秋雨,皆入我心

      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.

    首先,這個(gè)題目要明確如果gas[0] + gas[1] + ... + gas[n] >= cost[0] + cost[1] + .. + cost[n],那么這個(gè)題目一定有解。因?yàn)椋鶕?jù)條件移項(xiàng)可得:
    (gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0,由于最終結(jié)果大于等于零,因此一定可以通過加法交換律,得到一個(gè)序列,使得中間結(jié)果都為非負(fù)。因此可以將算法實(shí)現(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 閱讀(386) 評論(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
    但是并不能保證每一個(gè)(gas[i] - cost[i])都大于0

    有點(diǎn)疑惑。。。。  回復(fù)  更多評論
      

    主站蜘蛛池模板: 久久精品成人免费看| 亚洲免费日韩无码系列| 91大神免费观看| 亚洲人成在线播放网站岛国| a级毛片在线免费看| 亚洲中文字幕在线观看| 9久热这里只有精品免费| 2020久久精品亚洲热综合一本| 久久中文字幕免费视频| 亚洲三级电影网址| 免费精品国产自产拍在线观看图片 | 国产一级一片免费播放| 在线精品自拍亚洲第一区| 国产成人综合久久精品免费| 国产精品亚洲一区二区三区 | 国产成人精品免费视| 亚洲人成电影网站| 午夜dj在线观看免费视频| 黄色免费网址大全| 亚洲欧洲∨国产一区二区三区| 久久青草免费91线频观看不卡 | 亚洲精品无码av人在线观看| 最新亚洲成av人免费看| 亚洲理论在线观看| 在线精品免费视频| 亚洲精品无码久久久久| 最近2019免费中文字幕视频三| 亚洲av永久综合在线观看尤物| 国产禁女女网站免费看| 久久久久久久久久久免费精品| 亚洲久本草在线中文字幕| 亚洲免费人成视频观看| 免费一区二区无码视频在线播放| 亚洲欧洲成人精品香蕉网| 无码人妻一区二区三区免费| 色妞www精品视频免费看| 亚洲精品国产电影午夜| 免费在线观看黄网站| 国产在线jyzzjyzz免费麻豆| 一级做a爰片久久毛片免费陪 | 男女男精品网站免费观看 |