Tag Archives: algorithm

Remove array duplicate elements

design algorithm, in the array r[n] delete all elements whose element value is x, requiring time complexity of O(n); The spatial complexity is O(1).

#include<iostream>
using namespace std;

int Deletex(int r[],int n,int x)
{
    int j=0,k=0;
    for(int i=0;i<n;i++)
    {
        if(r[i]!=x)
        {
           r[j]=r[i];
           j++;
        }
        else
            k++;
    }
    return k;
}

int main()
{
    int r[1000];
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>r[i];
    int x;                        //输入要删除的元素
    cin>>x;
    int m=Deletex(r,n,x);
    for(int i=0;i<n-m-1;i++)
        cout<<r[i]<<" ";
    cout<<r[n-m-1];
    return 0;
}