[LeetCode] Move Zeroes

코테연습|2024. 9. 20. 13:32

https://leetcode.com/problems/move-zeroes/description/?envType=study-plan-v2&envId=leetcode-75

 

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.

 

Example 1:

Input: nums = [0,1,0,3,12]

Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]

Output: [0]

 

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

 

숫자가 들어간 배열이 있고, 0을 맨 뒤로 몰아서 정돈하는 문제.

단, 배열을 새로 만들어선 안되고 기존에 매개변수로 들어온 배열을 수정해서 문제를 풀어야 한다.

 

 

문제 풀이

function moveZeroes(nums) {
  let zeroCount = 0;

  for (let i = nums.length - 1; i >= 0; i--) {
    if (nums[i] === 0) {
      nums.splice(i, 1);
      zeroCount++;
    }
  }
  nums.push(...new Array(zeroCount).fill(0));
}

 

0의 개수를 센 다음, 해당 위치의 0은 지워버리고 다 돌고 난 다음에 0의 수만큼 뒤에 배열을 덧붙였다.

문제 제목이 Move Zeroes인데ㅋㅋㅋㅋ 내 풀이는 사실상 0을 움직인다기보단

그냥 지웠다가 추가하는 거라 문제의 취지에 반하는 것 같기도...

배열 관련 함수를 찾다가 알게 됐는데, Array.shift() 라는 함수가 있었다.

pop()과 정반대로 작동하는 함수고, 맨 앞의 엘리먼트를 날려버리면서 해당 엘리먼트를 리턴하는 함수다~

 

다른 풀이

var moveZeroes = function(nums) {
    let lastNonZeroIndex = 0
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] !== 0) {
            [nums[lastNonZeroIndex], nums[i]] = [nums[i], nums[lastNonZeroIndex]]
            lastNonZeroIndex++
        }
    }
    return nums
};

 

다른 풀이는 단순하게 그냥 위치를 바꿔줬다. [a, b] = [b, a] 로 그냥 단순하게......

배열 속 엘리먼트의 위치를 변경할 수 있다는 걸 까먹어서(...) 역시 안 쓰면 잊어버리는 법이군요.

 

아무튼 새로운 걸 알게 되었군요! 약간 성장!

'코테연습' 카테고리의 다른 글

[LeetCode] In Subsequence  (0) 2024.10.30
[LeetCode] String Compression  (0) 2024.09.20
[LeetCode] Increasing Triplet Subsequence  (0) 2024.09.19

댓글()