本文介绍了从未排序的数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,以从未排序的int数组中删除重复项.我有一个适用于更多示例的解决方案,但是由于以下输入而失败:

I'm trying to create a function to remove duplicates from an unsorted int array. I have a solution that works for more examples, but it's failing with the following input:

#include<iostream>
using namespace std;

int removeDuplicates(int arr[], int n)
{
    int j = 0;

    for (int i=0; i < n; i++){
        for(int j=0;j<=i;j++){

            if(arr[i]==arr[j]){
                 n--;
                for (int k=i; k<n; k++){
                    arr[k]=arr[k+1];
                }
            }
        }
    }

    return n;
}

// Driver code
int main()
{
    int arr[] = {0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    n = removeDuplicates(arr, n);

    for (int i=0; i<n; i++)
        cout << arr[i] << " ";

    return 0;
}

此arr示例的输出为0 0 1 0 0,应为0 1.

The output for this arr example is 0 0 1 0 0 and should be 0 1.

您看到问题出在哪里吗?谢谢

Do you see where is the problem? Thank you

推荐答案

查看您忘记减小 i

#include<iostream>
using namespace std;

int removeDuplicates(int arr[], int n)
{
    int j = 0;

    for (int i=0; i < n; i++){
        for(int j=0;j<i;j++){

            if(arr[i]==arr[j]){
                n--;
                for (int k=i; k<n; k++){
                    arr[k]=arr[k+1];
                }
                i--;     // you forgot to decrement i
            }
        }
    }

    return n;
}

// Driver code
int main()
{
    int arr[] = {0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    n = removeDuplicates(arr, n);

    for (int i=0; i<n; i++)
        cout << arr[i] << " ";

    return 0;
}

这篇关于从未排序的数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 09:39