Moved ZeroS

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:

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

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

나의 풀이

JavaScript

원본 배열에 변형을 주는 splice() 메서드와 push() 메서드를 사용했다. 배열 요소가 0일경우 splice 메서드를 통해 해당 요소는 삭제하고 push 메서드를 통해 0을 배열의 뒤쪽에 추가해줬다.

1
2
3
4
5
6
7
8
9
10
11
12
13
// 68ms
var moveZeroes = function(nums) {
let i = 0, l = nums.length;
while(i < l) {
if(nums[i] === 0) {
nums.splice(i, 1);
nums.push(0);
l--;
} else {
i++;
}
}
};

Python

자바스크립트에서 푼 풀이방법으로 list의 메서드를 이용해 풀었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = len(nums)
for i in range(l):
if nums[i] == 0:
nums.remove(0)
nums.append(0)
l -= 1
else:
i += 1

count() 메서드를 통해 0인 요소의 개수를 세어 그만큼 for문을 돌리는 방법을 사용했다.

1
2
3
4
5
6
7
8
9
10
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = nums.count(0)
for i in range(l):
nums.remove(0)
nums.append(0)

다른 사람 풀이

JavaScript

0이 아닌 요소만 다시 배열에 순서대로 담아주고, index부터 총 길이까지 0을 추가해줬다.

1
2
3
4
5
6
7
8
9
10
11
12
13
var moveZeroes = function(nums) {
var index = 0
for (var i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[index] = nums[i];
index++;
}
}

for (var i = index; i < nums.length; i++) {
nums[i] = 0;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
idx = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[idx], nums[i] = nums[i], nums[idx]
idx += 1

자바스크립트에서는 객체와 변수의 분해대입이 아니라면 변수를 ,(콤마)로 구분해 값을 한번에 할당할 수가 없는데, 파이썬에서는 가능하다.

1
2
3
4
5
6
7
8
9
10
const a, b = 1, 2; // 이것은 문법적으로 허용되지 않고
// Uncaught SyntaxError: Missing initializer in const declaration

const a = b = 1; // 이것은 b가 전역 변수가 되기 때문에 좋은 방법이 아니다.

// 대신 다음과 같은 객체와 배열의 분해대입은 가능하다.
const [a, b] = [1, 2]

const obj = {a: 1, b: 2}
const {a, b} = obj

파이썬에서는 다음과 같은 방법으로 변수를 만들 수 있다.

1
2
3
4
5
a, b = 1, 2
a, b = (1, 2)
(a, b) = 1, 2
[a, b] = [1, 2]
a = b = 'python'

Share Comments