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]
출처 :https://leetcode.com/problems/move-zeroes/description/
풀이
/**
Do not return anything, modify nums in-place instead.
*/
function moveZeroes(nums: number[]): void {
for (let i = 0, j = 0; i < nums.length; i++) {
if (nums[i] != 0) {
const x: number = nums[j];
nums[j] = nums[i];
nums[i] = x;
j++;
}
}
};
배열 nums의 모든 0 요소를 배열의 끝으로 이동시키는 함수. 이때, 배열의 다른 요소들의 상대적인 순서는 유지
ex) nums = [0, 1, 0, 3, 12]
1. 첫 번째 반복 (i = 0)
- nums[i]는 0이므로, 아무 작업도 하지 않고 다음 인덱스로 넘어감
nums = [0, 1, 0, 3, 12]
i = 1, j = 0
2. 두 번째 반복 (i = 1)
- nums[i]는 1로, 0이 아니므로 조건문이 실행
- x = nums[j]는 x = 0
- nums[j] = nums[i]는 nums[0] = 1
- nums[i] = x는 nums[1] = 0
- j를 1 증가
nums = [1, 0, 0, 3, 12]
i = 2, j = 1
3. 세 번째 반복 (i = 2)
- nums[i]는 0이므로, 아무 작업도 하지 않고 다음 인덱스로 넘어감
nums = [1, 0, 0, 3, 12]
i = 3, j = 1
4. 네 번째 반복 (i = 3)
- nums[i]는 3로, 0이 아니므로 조건문이 실행
- x = nums[j]는 x = 0
- nums[j] = nums[i]는 nums[1] = 3
- nums[i] = x는 nums[3] = 0
- j를 1 증가
nums = [1, 3, 0, 0, 12]
i = 4, j = 2
5. 다섯 번째 반복 (i = 4)
- `nums[i]는 12로, 0이 아니므로 조건문이 실행
- x = nums[j]는 x = 0
- nums[j] = nums[i]는 nums[2] = 12
- nums[i] = x는 nums[4] = 0
- j를 1 증가
nums = [1, 3, 12, 0, 0]
i = 5, j = 3'LeetCode' 카테고리의 다른 글
| 1219. Path with Maximum Gold / TypeScript (0) | 2024.06.22 |
|---|---|
| 2248. Intersection of Multiple Arrays / TypeScript (0) | 2024.06.20 |
| 590. N-ary Tree Postorder Traversal / TypeScript (1) | 2024.06.18 |
| 1431. Kids With the Greatest Number of Candies / TypeScript (0) | 2024.06.16 |
| 3046. Split the Array / TypeScirpt (0) | 2024.06.15 |