"Move Zeroes - Problem 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.
Example Usage :
Let's consider a few examples to understand how the MoveZeroes method works :
Example 1 :
Input : nums = [0,1,0,3,12]
Output : [1,3,12,0,0]
Example 2:
Input : nums = [0]
Output : [0]
Solution Overview : 🧾
To solve this problem, we can use an improved in-place algorithm:
1. Initialize an index variable to keep track of the position where the next non-zero element should be placed.
2. Iterate through the array with another pointer i.
3. If nums[i] is non-zero, swap nums[index] with nums[i] and increment index.
4. After the loop, all non-zero elements will be placed at the beginning of the array, and all zeros will be at the end.
Implementation in C# :
public class Solution
{
public void MoveZeroes(int[] nums)
{
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums.Length > 1 && nums[i] != 0)
{
int temp = nums[index];
nums[index] = nums[i];
nums[i] = temp;
index++;
}
}
}
}
Example Usage :
Provide examples using the MoveZeroes method with sample input arrays and expected output.
0 Comments