A strange problem.

• The following code can get Accepted:

``````class Solution {
public:
int removeDuplicates(int A[], int n) {
int m=0;
if (n==0) return 0;
for (int i=0;i<n;i++)
{
int j=i;
while ((i+1<n)&&(A[i+1]==A[i])) i++;
if (i!=j) m+=2; else m++;
}
int k=0;
for (int i=0;i<n;i++)
{
int j=i;
while ((i+1<n)&&(A[i+1]==A[i])) i++;
if (i!=j) {A[k]=A[k+1]=A[j];k+=2;} else A[k++]=A[j];
}
//free(A+m);
return m;
}
};`
``````

But the following code would get RE

``````    class Solution {
public:
int removeDuplicates(int A[], int n) {
int m=0;
if (n==0) return 0;
for (int i=0;i<n;i++)
{
int j=i;
while ((i+1<n)&&(A[i+1]==A[i])) i++;
if (i!=j) m+=2; else m++;
}
int *B=(int*)malloc(m*sizeof(int));
int k=0;
for (int i=0;i<n;i++)
{
int j=i;
while ((i+1<n)&&(A[i+1]==A[i])) i++;
if (i!=j) {B[k]=B[k+1]=A[j];k+=2;} else B[k++]=A[j];
}
free(A);
A=B;
return m;
}
};
``````

1. there are duplicated unformatted code in the last
2. explain algorithm
3. make comment in code

• This post is deleted!

• You shouldn't create another array and free the array `A`.

And `A=B;` does not make sense because it won't change the array that passed in.

So when the judge try to free the array `A`, it cause Runtime Error.

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