简体   繁体   中英

Is there any leak in my code, Only 1 case isn't working I don't know why?

I am trying to write a programme to move all the zeroes at the end of the array and retain and the original order of other elements.

Here is my code:-

var moveZeros = function (arr) {

  // TODO: Program me

var k=0;
  for (var i=0;i<=arr.length-1;i++){
    
    var s=arr[i];
    if (s===0){
      
      arr.splice(i,1);
      k++
      
      }
    }
for (var j=0;j<=k-1;j++){


    arr.push(0);


    }

  return arr

  }

But when zeros are next to each other like [1,0,0,1] it doesn't work.

I don't see why.

Can anybody tell?

And please also explain why k-1 not k I wrote k-1 by observing the output. Please don't tell the answer to the original problem I just want to fix the problem with my code. :)

The problem is that in each loop you increase the i variable by one. Meaning, you go to the next index. But if you have 2 or more zeros in the row, and you remove the first one, you shouldn't change i to i + 1 , because i already points at a new value in the array(which is zero):)

var moveZeros = function (arr) {
  // TODO: Program me

  var k = 0;
  for (var i = 0; i <= arr.length - 1;) {
    var s = arr[i];
    if (s === 0) {
      arr.splice(i, 1);
      k++;
    } else {
      i++;
    }
  }
  for (var j = 0; j <= k - 1; j++) {
    arr.push(0);
  }

  return arr;
};

console.log(moveZeros([1,0,0,2]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM