Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save guolinaileen/4670376 to your computer and use it in GitHub Desktop.
Save guolinaileen/4670376 to your computer and use it in GitHub Desktop.
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array A = [1,1,2], Your function should return length = 2, and A is now [1,2].
public class Solution {
public int removeDuplicates(int[] A) {
int length=A.length;
if(length==0 || length==1) return length;
int i=1;
for(int j=1; j<length; j++)
{
if(A[j]!=A[j-1])
{
A[i]=A[j];
i++;
}
}
if(i<length) A[i]='\0';
return i;
}
}
@Manuel4131
Copy link

Hi, if I try to solve the problem in C. I need a variable to store the length of the array. Is it against the subject's rule?

@dishbreak
Copy link

@Manuel4131, no, because that counts as constant memory. Regardless of array size, you'll only need the one variable to store its length.

@abhilater
Copy link

Your solution is not correct, will fail for say [0,0,0,1,1]

@Vargha
Copy link

Vargha commented Jan 21, 2018

class Solution {
public int removeDuplicates(int[] nums) {
int i=0, j=0;
int dup=0; // number of duplicates in nums[]
while (j+1 < nums.length){
if (nums[j] == nums[j+1]){
j++;
dup++;
}else{
j++;
nums[++i] = nums[j];
}
}
return nums.length - dup;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment