134. 加油站-----O(N)遍历发法

解法思路来源

中心是抓住 sum(gas)一定 >= sum(cost) 才能跑完这一点来完成的
但是 加入了一个curr 来 选当前站点是否可以走完循环 如果cur< 0 则不可以 ,接着讲start 替换即可

class Solution {
  public int canCompleteCircuit(int[] gas, int[] cost) {
    int n = gas.length;

    int total_tank = 0;
    int curr_tank = 0;

    int start = 0;
    for (int i = 0; i < n; ++i) {
      total_tank += gas[i] - cost[i];
      
      curr_tank += gas[i] - cost[i];
     
      if (curr_tank < 0) {
        
        start = i + 1;
        
        curr_tank = 0;
      }
    }
    return total_tank >= 0 ? start : -1;
  }
}


发布了89 篇原创文章 · 获赞 3 · 访问量 5745

猜你喜欢

转载自blog.csdn.net/Hqxcsdn/article/details/104609558