Monday, March 10, 2014

LeetCode: Remove Duplicates from Sorted Array I&&II



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].



Solution:

惊艳!One time pass.....


public int removeDuplicates(int[] A) {
if(A == null || A.length ==0) return 0;
int len = A.length;
int moveForward =0;
int finLen =1;
for(int i=1; i<len; i++){
while(i<len && A[i]==A[i-1]){
//find a duplicate, use moveForward to indicate how many items to be deleted
//The new index of next new item would be i-moveForward
moveForward++;
i++;
}
if(i==len) return finLen;
if(moveForward>0)
A[i-moveForward] = A[i];
finLen++;
}
return finLen;
}
view raw gistfile1.java hosted with ❤ by GitHub
上面的这种方法在解决II的时候变得无比dumb. 其实还有更简单漂亮的解法 双指针 can be considered as double pointers problem

//solution for I
public int removeDuplicates(int[] A) {
if(A == null || A.length ==0) return 0;
int newEndIndex=0;
for(int i=1; i<A.length; i++){
if(A[i]!=A[newEndIndex])
A[++newEndIndex]=A[i];
}
return newEndIndex+1;
}
////solution for II
public int removeDuplicates(int[] A) {
if(A == null || A.length ==0) return 0;
int newEndIndex=0;
int occurTimes=1;
for(int i=1; i<A.length; i++){
if(A[i]==A[newEndIndex]){
if(occurTimes>=2) continue;
occurTimes++;
}
else
occurTimes=1;
A[++newEndIndex]=A[i];
}
return newEndIndex+1;
}
view raw gistfile1.java hosted with ❤ by GitHub

No comments:

Post a Comment