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.....
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 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; | |
} |
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
//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; | |
} |
No comments:
Post a Comment