-
[알고리즘] #Move Zeroes■ Algorithm 2022. 8. 3. 23:19
문제 출처: https://leetcode.com/problems/move-zeroes/
Move Zeroes - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 해석
정수형 배열 nums가 주어졌을 때, 0이 아닌 요소들은 상대적인 순서를 유지하면서 모든 0을 배열 끝으로 이동하라.
NOTE: 배열을 복사하지말고 그대로 사용해야한다.
풀이
0이 아닌 숫자를 만날 때마다 크기가 1씩 증가하는 nonZero 라는 정수형 변수를 선언한다.
nums 배열을 순회하면서 요소 값이 0이 아닌 경우, nums[nonZero]을 요소 값으로 치환한 뒤, nonZero의 값을 1씩 증가시켜준다.
순회가 끝나게되면 nums 배열은 앞 부분에 0이 아닌 요소들이 순서대로 나열되어있다.
nonZero부터 nums 배열 끝 부분은 0인 원소만 남아있어야하므로 요소의 값을 모두 0으로 바꿔준다.
var moveZeroes = function(nums) { let nonZero = 0; for (let i=0; i<nums.length; i++) { if (nums[i] !== 0) { nums[nonZero] = nums[i]; nonZero += 1; } } for (let i=nonZero; i<nums.length; i++) { nums[i] = 0; } };
'■ Algorithm' 카테고리의 다른 글
[알고리즘] #Reverse String (0) 2022.08.05 [알고리즘] #Two Sum II - Input Array Is Sorted (0) 2022.08.05 [알고리즘] Rotate Array (0) 2022.08.02 [알고리즘] #Squares of a Sorted Array (0) 2022.08.02 [알고리즘] #Search Insert Position (0) 2022.08.01