codewars 小记 :除去诡异多端的0

126 阅读2分钟

ISSUE

Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred.

For example, the following array

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]

is transformed into

[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

Zero elements are defined by either 0 or "0". Some tests may include elements that are not number literals.

You are NOT allowed to use any temporary arrays or objects. You are also not allowed to use any Array.prototype or Object.prototype methods.

describe("Tests", () => {
  it("test", () => {
var input = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14],
    solution = [7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0];

Test.assertEquals(JSON.stringify(removeZeros(input)), JSON.stringify(solution));
  });
});

翻译

编写一个函数,该函数接受一个值数组,并将所有为零的元素移动到数组的末尾,否则保留数组的顺序。零元素还必须保持它们发生的顺序。

零元素由0或“0”定义。有些测试可能包含非数字文字的元素。 不允许使用任何临时数组或对象。您也不允许使用任何数组。原型或物体。原型方法。

//对“数组”进行排序,使值为零的所有元素都移动到数组的//末尾,而其他元素保持顺序。//[0,1,2,0,3]-->[1,2,3,0,0]//零元素也保持它们出现的顺序。//[0,“0”,1,2,3]-->[1,2,3,0,“0”]//不要使用任何临时数组或对象。此外,您不能//使用任何数组或对象原型方法,例如。shift()。push()等//应返回正确排序的数组。

前奏

这道题有意思,不使用原型方法,也不能用任何临时数组或对象 还必须保持它们发生的顺序,那么这种稳定的方法大概率要使用较为朴素的方法了

解题:

/**
 * @author zowie
 * @param {array} array
 * @return {array} array
 */
function removeZeros(array) {
  let flag = 0, len = array.length
  for (i = len - 1; i >= 0; i--) { //寻找诡异多端的0,如果找到了还要判断有没有需要移动的
    if (array[i] == 0 || array[i] == '0') {
      if (i + flag < len - 1) {
        let temp = array[i] //把0先拎出来,空出位置
        for (j = i + 1; j < len - flag; j++) { //把非零元素向前移动一位
          array[j - 1] = array[j]
          console.log(array)
        }
        array[len - flag - 1] = temp
        flag++
      }
    }
  }
  return array;
}

console.log(removeZeros([7, 2, 3, " 0", 4, 6, 0, '0', 13, 0, 78, 0, 0, 19, 14]));

//若可以另辟空间
function removeZeros(array) {
  const head = []
  const tail = []
  for (const e of array) {
    if (e === 0 || e === "0") {
      tail[tail.length] = e
    } else {
      head[head.length] = e
    }
  }
  return [...head, ...tail]
}