Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save luoxiaoxun/5802035 to your computer and use it in GitHub Desktop.

Select an option

Save luoxiaoxun/5802035 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].
C++:
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0||n==1) return n;
int min=A[0]-1;
for(int i=n;i>0;i--)
if(A[i]==A[i-1])
A[i]=min;
int index=0;
for(int i=0;i<n;i++)
if(A[i]!=min)
A[index++]=A[i];
return index;
}
};
Java:
public class Solution {
public int removeDuplicates(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A.length==0||A.length==1) return A.length;
int min=A[0]-1;
for(int i=A.length-1;i>0;i--)
if(A[i]==A[i-1])
A[i]=min;
int index=0;
for(int i=0;i<A.length;i++)
if(A[i]!=min)
A[index++]=A[i];
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment