美文网首页
8.19 gasStation

8.19 gasStation

作者: 陈十十 | 来源:发表于2016-08-21 03:37 被阅读8次

  • 暴力法 timeout
  • better
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = cost.size(), sum;
        for (int start=0; start<n;) {
            if (gas[start]-cost[start] < 0) {
                ++start;
                continue;
            } 
            sum = 0;
            int j=start;
            for (; j<start+n; ++j) {
              sum += gas[j%n]-cost[j%n];
              if (sum<0) break;
            }
            if (j==start+n) return start;
            else start = j;
        }
        return -1;//should never be
    }

诶居然想这么久,想到要把gas[i]-cost[i],而且正确的starti此数不能是负的。然而没考虑好然后怎么才能从O(n^2)回到O(n)。

  • We are looking for if we can find a starti that allows us to traverse without ever getting negative gas total, meaning we can safely get to any gas station starting from here.
  • ~Given if there's solution it must be unique, there's only one starti that can reach all other stations while other stations can not safely reach starti.~ (can used this property to eliminate answer)
  • So if we start at some index tryi, and end up out of gas at index tryi+m: we know tryi and tryi+m cannot be the answer. Moreover, any index in between cannot be neither. (cuz of property above)

相关文章

  • 8.19 gasStation

    暴力法 timeout better 诶居然想这么久,想到要把gas[i]-cost[i],而且正确的starti...

  • 手绘05

    景观手绘, 8.18 8.19

  • 刷题

    8.19 530+15+356

  • 8月

    8.19.沈阳固驰培训 8.17

  • 2015欧洲之旅

    2015.8.5—8.19 8 月5日斯里兰卡 ...

  • Descartes

    dubito ergo cogito: cogito ergo sum 8.19

  • 哎!

    8.19 雨 哎!这个就是今天的心情。

  • 梦回天池~行程记录

    2018.8.12.-8.19.武汉–沈阳–长白山 行:

  • 8.19

    一个破碎的我 拿什么拯救一个 同样破碎的你 对不起 是我无能

  • 8.19

    忙碌的一天结束了,早点睡吧小奶狗。

网友评论

      本文标题:8.19 gasStation

      本文链接:https://www.haomeiwen.com/subject/zecisttx.html