개발이 취미인 주니어 기획자

[투포인터][JavaScript][LeetCode] #283. Move Zeros 본문

문제 풀이/알고리즘 문제 풀이

[투포인터][JavaScript][LeetCode] #283. Move Zeros

큐 2023. 3. 31. 14:00
728x90
반응형

#투포인터  #EASY

 

Move Zeroes - LeetCode

Can you solve this real interview question? Move Zeroes - Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.   E

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Move Zeros
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.


🎃 제한 사항
1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31 - 1

입출력 예

nums result
[0, 1, 0, 3, 12] [1, 3, 12, 0, 0]
[0] [0]

 

🌷 내 코드

1. 투포인터

자바스크립트
타입스크립트는 이제 안 해봐도 될듯... 런타임 항상 김!

var moveZeroes = function (nums) {
  let left = 0;
  let right = 1;


  while (right < nums.length) {
    if (nums[left] === 0 && nums[right] !== 0) { // 0 두 개가 연속으로 나오지 않는 경우
      let temp = nums[left];
      nums[left] = nums[right];
      nums[right] = temp; // 0을 오른쪽으로 옮겨주고
      left++; // 왼쪽도 다른 숫자로 갈 수 있도록 옮겨줌
    }

    if (nums[left] !== 0) { // 0이 아니면 
      left++; // 왼쪽도 오른쪽으로 옮겨줌
    }

    right++; // 두개 연속 0일 경우 pointer2를 오른쪽으로 옮겨줌
  }
};

2. 무지성

차이 너무 많이나자나 >< 구현만 하면 되는 줄 알았던 과거의 나 반성

var moveZeroes = function (nums) {
  let zeroCnt = 0;
  nums.forEach((n) => {
    if (n === 0) {
      zeroCnt++;
    }
  });

  for (let i = 0; i < zeroCnt; i++) {
    let idx = nums.indexOf(0);
    nums.splice(idx, 1);
    nums.push(0);
  }
};

 

🌷 코멘트

투포인터는 알고리즘은 간단한데, 이외에도 문제에서 요구하는 걸 잘 읽어서 파악하는것이 중요한 것 같다
근데 파악이 안됨.. 예외케이스마다 다 틀리고 그것때문에 조건문을 계속 추가하는 듯;
머리로 잘 안 그려질 땐 주석으로라도 케이스를 눈으로나마 돌려가면서 고민해 보는 것두 나쁘지 않음 + 손으로 그리는건 더 좋고!
👉 미리 예외케이스를 생각해보려고 하자!

 

 


블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형