Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/7416865 to your computer and use it in GitHub Desktop.
Save charlespunk/7416865 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(A.length == 0) return 0;
int writer = 0;
int reader = 1;
while(reader != A.length){
if(A[reader] == A[writer]) reader++;
else A[++writer] = A[reader++];
}
return writer + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment