리트코드/easy
[리트코드] 283. Move Zeroes - js (투포인터)
bbeyak
2023. 8. 17. 17:23
반응형
1. 문제
https://leetcode.com/problems/move-zeroes/description/
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
2. 코드
처음 작성한 코드) 오답
nums = [0,0,1] 일 경우 답이 [0,1,0]이 된다. 그 이유는 2중 for문의 조건 때문이다. 맨 처음 0은 첫 for문 이후 움직임이 없이 그 자리 그대로 남아 오답처리가 된다.
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
for(let i=0;i<nums.length-1;i++){
for(let j=i;j<nums.length-1;j++){
if(nums[j] === 0){
nums[j] = nums[j+1];
nums[j+1] = 0;
}
}
}
};
정답)
이 문제의 핵심은 연속적인 0이다. 연속된 0의 처리를 위해 투포인터를 사용한다. 0의 연속이 끝난 지점의 요소와 0의 연속이 시작되는 지점의 요소를 바꿔주면 끝!
var moveZeroes = function(nums) {
let low = 0;
let high = low + 1;
while (high <= nums.length - 1) {
if (nums[low] !== 0) {
low++;
high++;
} else {
if (nums[high] !== 0) {
[nums[low], nums[high]] = [nums[high], nums[low]];
low++;
}
high++;
}
}
};
Easy 문제라면서 왠 투포인터!ㅜㅜ
참고한 글)
https://leetcode.com/problems/move-zeroes/solutions/2685367/js-es6-two-pointers-93-with-explanation/
반응형