Day 42: Li Kou question 134, gas station

Address: leetcode-cn.com/problems/ga…

If the sum is less than zero, oil will not be enough. If the sum is greater than zero, oil will be enough. So you add them, you go over them, and you find a place where you don’t end with zero.

var canCompleteCircuit = function(gas, cost) {
  let res = [];
  let flag = -1;
  let sum = 0;
  let ser = 0;
  for(let i = 0; i < gas.length; i++)
  {
    res[i] = gas[i] - cost[i];
  }
  if(res.reduce((prev, next, index, array) => prev + next) < 0)
  {
    return -1;
  }
  for(let i = 0; i < res.length; i++)
  {
    if(flag === -1 && res[i] > 0)
    {
      sum = res[i];
      ser = i;
      flag = 0;
    }
    else if(flag === 0)
    {
      sum += res[i];
    }
    if(sum < 0)
    {
      flag = -1;
    }
  }
  return ser;
};
Copy the code
Execution time: 84 ms, beating 75.81% of users in all JavaScript commits
Memory consumption: 39.4 MB, beating 8.27% of all JavaScript commits

If you’re operating on an array, it’s going to consume less memory, so I’ll give cost a null.

Execution time: 80 ms, beating 87.67% of users in all JavaScript commits
Memory consumption: 38.1 MB, beating 36.33% of all JavaScript commits

Ha ha ha ha ha, smart as me.