Remove Zeros

SungJunEun·2021년 11월 27일
0

Codewars 문제풀이

목록 보기
24/26
post-thumbnail

Description:

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.

My solution:

function removeZeros(array) {
  let zeros = 0;
  for(i=0;i<array.length;i++){
    if(array[i] === 0 || array[i] === '0'){
      zeros++;
    }
  }

  let value;
  let counter = 0;
  console.log(array);
  while(counter < zeros)  {
    for(i=0;i<array.length;i++){    
    if((array[i] === 0 || array[i] === '0') && array[i+1] !== undefined) {
      value = array[i];
      array[i] = array[i+1];
      array[i+1] = value;
    }
  }
    counter++;
}
  return array;
}

Best solutions:

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]
}
  • spread operator 오브젝트를 깊은 복사할 수 있다. 여기서 깊은 복사란, 동일한 프로퍼티를 가지지만, 아예 다른 주소를 갖는 객체를 만드는 것을 말한다. 하지만, nested된 형태라면 깊은 복사가 안된다.
    a = [1,2,[3,4]];
    b = [...a];
    b[2].push(5);
    console.log(a); // [1,2,[3,4,5]] shallow copy!
profile
블록체인 개발자(진)

0개의 댓글