Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only onceand 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].
public class Solution {
public int removeDuplicates(int[] A) {
int len=A.length;
if(len<2) return len;
int j=0;
for(int i=1;i<len;){
if(A[i]==A[j])
i++;
else
A[++j]=A[i++];
}
return j+1;
}
}
Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
1. The same solution imitating the above one
public class Solution {
public int removeDuplicates(int[] A) {
int len=A.length;
if (len<3)
return len;
int pre = A[0];
boolean flag = false;
int count = 0;
// index for updating
int j = 1;
for (int i = 1; i < len; i++) {
int cur = A[i];
if (cur == pre) {
if (!flag) {
flag = true;
A[j++] = cur;
continue;
} else {
count++;
}
} else {
pre = cur;
A[j++] = cur;
flag = false;
}
}
return A.length - count;
}
}
2. Better solution
public class Solution {
public int removeDuplicates(int[] A) {
int len=A.length;
if(len<3)
return len;
int pre=1;
int cur=2;
while(cur<len){
if(A[cur]==A[pre]&&A[cur]==A[pre-1]){ // There are three consecutive same values
cur++;
}else{
pre++;
A[pre]=A[cur];
cur++;
}
}
return pre+1;
}
}