Created
November 11, 2013 17:22
-
-
Save charlespunk/7416865 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 hidden or 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
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