# move zeroes and remove repeated from array

• Given an array nums, which is sorted (besides 0 in between numbers), write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements and maintaining only one copy of each non-zero element.

For example, given nums = [0, 1, 1, 0, 3, 3, 0, 3, 4, 5, 0, 5, 5, 12], after calling your function, nums should be [1, 3, 4, 5, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0].

• ``````int i1 = 0, i2 = 0, pre = 0;
while (i2 < nums.length) {
if (nums[i2] == pre || nums[i2] == 0) {
i2 ++;
} else {
nums[i1++] = nums[i2];
pre = nums[i2++];
}
}

for (int i = i1; i < nums.length; i ++) {
nums[i] = 0;
}
``````

• public void moveZeroes(int[] nums) {

``````int i=0;

while(nums[i]!=0 && i < nums.length -1){
i++;
}

for(int j = i+1; j< nums.length  ; j++){
if(nums[j]!=0){
nums[i] = nums[j];
nums[j] = 0;
i++;
}
}
``````

}

• ``````     public static int[] removeZeroRepeat(int[] arr)
{
int j = 0;
int[] narr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
if(arr[i]!=0) { narr[j] = arr[i];j++; }
}

int dist = narr.Distinct().ToArray().Length;
int zero = arr.Length - dist;
int[] res = new int[dist-1+zero];
int[] x= narr.Distinct().ToArray();
for (int i = 0; i < res.Length; i++)
{
if (i < dist)
res[i] = x[i];
else res[i] = 0;
}

return res;
}``````

• ``````public void moveZeros(int[] nums)
{
if(nums==null || nums.length==0) return ;

int i=0;int j=0;int prev=INTEGER.MIN_VALUE;

while(i<nums.length && j< nums.length)
{
if(nums[j] !=0 && nums[j] !=prev)
{
prev=a[j];
a[i++]=a[j];
}
j++;

}

for(int k=i;k<nums.length;k++)
{
nums[k]=0;
}

}

``````

• This post is deleted!

• ``````public static int[] removeDuplicates(int[] nums) {
int prev = 0;
int pos = 0;

for(int i = 0; i < nums.length; i++) {
if(nums[i] != 0 && nums[i] != prev) {
nums[pos++] = nums[i];
prev = nums[i];
} else {
nums[i] = 0;
}
}

for(int i = pos; i < nums.length; i++) {
nums[i] = 0;
}

return nums;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.