8.19 gasStation

  • 暴力法 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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,096评论 18 399
  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 5,249评论 0 6
  • “啊呀~!”“啊~!”⋯高一六班中传来了一阵阵可怕的叫声。全班中一半的人都被收到了“...
    陈琳璐阅读 3,077评论 0 1
  • 今天在西安受邀参加美乐家服务商大会,两款新品发布,今年还会再发布30余款新品。团队很多伙伴上台接受表彰,非常开心,...
    耿峰丰盛部落创始人阅读 3,134评论 0 0