Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input:[0,1,0,3,12]Output:[1,3,12,0,0]
public class Solution {
public void MoveZeroes(int[] nums) {
int pos = -1;
for (int i = 0; i < nums.Length; i++)
{
if (pos == -1 && nums[i] != 0) continue;
if (nums[i] == 0 && pos == -1)
{
pos= i;
continue;
}
else if(nums[i]!=0)
{
nums[pos] = nums[i];
nums[i] = 0;
pos = pos + 1;
}
}
}
}
Time Complexity-o(1).
Space Complexity – o(1),