设为首页 加入收藏

TOP

Gas Station [leetcode] 的两种解法
2015-07-20 17:31:59 来源: 作者: 【 】 浏览:2
Tags:Gas Station leetcode 解法

由于gas总量大于cost总量时,一定可以绕所有城市一圈。

第一种解法:

假设一开始有足够的油,从位置i出发,到位置k时剩余的油量为L(i,k)。

对任意的k,L(i,k)根据i的不同,只相差常数。

我们只需要找到最小的L(0, k)对应的k,k+1为所求。

代码如下:

    int canCompleteCircuit(vector
  
    &gas, vector
   
     &cost) { int start = 0; int curGas = 0, minGas = 0, totalGas = 0; for (int i = 0; i < gas.size(); i++) { int temp = gas[i] - cost[i]; curGas += temp; totalGas += temp; if (minGas > curGas) { start = i + 1; minGas = curGas; } } if (totalGas >= 0) return start % gas.size(); else return -1; }
   
  

第二种解法:

如果L(i,k) < 0,则从i和k之间所有的位置都不能到k

所以从k+1的位置从0开始找

    int canCompleteCircuit(vector
  
    &gas, vector
   
     &cost) { int start = 0; int curGas = 0, totalGas = 0; for (int i = 0; i < gas.size(); i++) { int temp = gas[i] - cost[i]; curGas += temp; totalGas += temp; if (curGas < 0) { start = i + 1; curGas = 0; } } if (totalGas >= 0) return start % gas.size(); else return -1; }
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Effective C++ 29-33 下一篇Codeforces Round #271 (Div. 2) ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)