Created
January 30, 2013 03:34
-
-
Save guolinaileen/4670376 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
public class Solution { | |
public int removeDuplicates(int[] A) { | |
int length=A.length; | |
if(length==0 || length==1) return length; | |
int i=1; | |
for(int j=1; j<length; j++) | |
{ | |
if(A[j]!=A[j-1]) | |
{ | |
A[i]=A[j]; | |
i++; | |
} | |
} | |
if(i<length) A[i]='\0'; | |
return i; | |
} | |
} |
@Manuel4131, no, because that counts as constant memory. Regardless of array size, you'll only need the one variable to store its length.
Your solution is not correct, will fail for say [0,0,0,1,1]
class Solution {
public int removeDuplicates(int[] nums) {
int i=0, j=0;
int dup=0; // number of duplicates in nums[]
while (j+1 < nums.length){
if (nums[j] == nums[j+1]){
j++;
dup++;
}else{
j++;
nums[++i] = nums[j];
}
}
return nums.length - dup;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, if I try to solve the problem in C. I need a variable to store the length of the array. Is it against the subject's rule?