Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 15, 2013 16:44
Show Gist options
  • Save zhoutuo/4961626 to your computer and use it in GitHub Desktop.
Save zhoutuo/4961626 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].
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int newLength = 0;
if(n == 0) {
return newLength;
}
int pre = A[0];
int newPos = 1;
++newLength;
for(int i = 1; i < n; ++i) {
if(pre != A[i]) {
++newLength;
pre = A[i];
A[newPos] = A[i];
++newPos;
}
}
return newLength;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment