Codewars|Moving Zeros To The End

152 阅读1分钟

DESCRIPTION:

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]

思路:

我的思路是双指针,一个指针从头到尾,一个指针从尾到头,遇上非0元素,交换两个指针对应的元素,直到两个指针重合。 后来看到其他人的解题思路,发现是我想复杂了......

Solution:

我的解法:

function moveZeros(arr) {
  const length = arr.length;
  let idx = 0;
  let zeroIdx = length - 1;
  
  
  while (idx <= zeroIdx) {
    const val = arr[idx];
    if (val === 0) {
      arr.splice(idx, 1);
      arr.push(0);
      zeroIdx--;
    } else {
      idx++;
    }
  }
  return arr
}

高赞解法:

var moveZeros = function (arr) {
  return [
    ...(arr.filter(n => n !== 0)),
    ...(arr.filter(n => n === 0))
  ];
}

万万没想法的解法:

function moveZeros(array) {
  return array.sort((a, b) => -(b === 0));
}