2024. 9. 23. 10:51ㆍ알고리즘/Leetcode
Solution
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.
Examples

Explanation
class Solution {
public void moveZeroes(int[] nums) {
int idx = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
nums[idx++] = nums[i];
}
}
for(int i = idx; i < nums.length; i++){
nums[i] = 0;
}
}
}
Create a variable, idx, to keep track of the position where the next non-zero element should be placed. This starts from the beginning of the array (idx = 0).
Using the first for loop, if the certain element is not zero, move it to the position idx, and then increment idx. This ensures that all non-zero elements are shifted to the front of the array in their original order.
After all non-zero elements are placed at the front, the remaining positions in the array (from idx to the end) should be filled with zeroes. This is done by iterating from idx to the end of the array and assigning 0 to those positions.
'알고리즘 > Leetcode' 카테고리의 다른 글
| Valid Sudoku (2) | 2024.10.04 |
|---|---|
| Two Sum (1) | 2024.09.24 |
| Plus One (2) | 2024.09.20 |
| Intersection of Two Arrays II (1) | 2024.09.12 |
| Single Number (2) | 2024.09.05 |