Can my Java solution be improved?

• My two pointers solution with O(n) time+ O(1) space.
The idea is to user 2 pointers. j finds out each different element it meets. i record the insert position of the next different element and eventually it records the length of the new Array without duplicate.

This is accepted. Just want to know is there any better algorithms or thoughts.

``````public class Solution {
public int removeDuplicates(int[] A) {
if(A.length<=1)return A.length;
int i = 0;
int j = 0;
int cur = A[j];
while(j<A.length){
if(A[j]!=cur){
cur = A[j];
A[i+1] = cur;
i++;
}
j++;
}
return i+1;
}
}``````

• Based on this idea, my code is:

``````public class Solution {
public int removeDuplicates(int[] A) {
if (A.length<=1) return A.length;
int i=0, j=0;
while (j<A.length){
if (A[j]!=A[i]){
i++;
A[i]=A[j];
}
j++;
}
return i+1;
}
}``````

• My code is here

``````public static int removeDuplicates(int[] A) {
int len = A.length;
for (int i = 0, j = 1; i < A.length && j < A.length; ) {
if (A[i] == A[j]) {
j++;
--len;
}else{
i++;
A[i]=A[j++];
}
}
return len;
}
``````

just using two pointer to move the element.

• ``````public int removeDuplicates(int[] A) {
int count = 0;
for(int i = 1; i < A.length; i++)
if(A[count] != A[i])
A[++count] = A[i];
return A.length == 0 ? 0 : count + 1;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.