Created
February 15, 2013 16:44
-
-
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].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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