从数字数组中删除重复

Removing duplicates from an array of numbers

本文关键字:删除 数字 数组      更新时间:2023-10-16

我正在尝试在C 中编写一个程序,其中我将一系列数字输入a[],然后将数字输出到b[]中,以删除任何重复项。例如,a[] = {1,3,7,6,3,7}将输出b[] = {1,3,7,6}。谢谢!

int main() {
  int a[10];
  int i, n, j;
  cout << "n=";
  cin >> n;
  for (i = 0; i <= n - 1; i++) {
    cout << "a[" << i << "]=";
    cin >> a[i];
  }
  for (i = 0; i < n; i++)
  {
    for (j = i + 1; j < n; j++)
    {
      if (a[i] == a[j]) {
        cout << "b= " << a[i] << endl;
      }
    }
  }
  for (i = 0; i <= n; i++) {
    if (a[i] != a[j]) {
      cout << "b=" << a[i] << endl;
    }
  }
}

如果您想摆脱副本(并保留订单(,则C 的惯用方式是使用std :: set :: set and std :: vector(在此处仅显示相关的smippet为您的示例(:

int a[] = {1,3,7,6,3,7};
std::set<int> c;
std::vector<int> b;
for(auto v: a)
 if(c.insert(v).second)
  b.push_back(v);
for(auto v: b)
 std::cout << v << std::endl; 

输出:

1
3
7
6

您的代码应更改为此(数组的顺序在代码片段中都不会尊重(:

  for (i = 0; i < n; i++) {
    bool notDup = true;
    for (j = i + 1; j < n; j++) {
      if (a[i] == a[j]) {
          notDup = false;
          break;
      }
    }
    if(notDup)
        cout << "b= " << a[i] << endl;
  }

但是,解决问题的解决方案是构建std::set,它将省略重复项。

vector<int> a{1,3,7,6,3,7};
set<int> b(a.begin(), a.end());
for (auto& elem : b)
{
    std::cout<<elem<<'n';
}

live

使用std::unordered_set跟踪您已经保留的元素。另外,使用std::vector代替C风格数组。

vector<int> a{1, 3, 7, 6, 3, 7}, 
            b;
unordered_set<int> s;
for(auto i : a)
{
    if (s.insert(i).second)
    {
        b.push_back(i);
    }
}

有很多方法可以从向量中删除重复项。

Oblivion解决方案中,简单的方法将它们插入集合,然后从集合中获取值。

vector<int> a{1,3,7,6,3,7};
set<int> b(a.begin(), a.end());
for (auto& elem : b)
{
    std::cout<<elem<<'n';
}

另一种方法是在STL中使用唯一。如果您不想使用更多的内存,那么此解决方案是完美的。时间复杂性是O(nlogn)

vector<int> a{1,3,7,6,3,7};
sort(a.begin(), a.end()); 
a.erase(unique(a.begin(), a.end()), a.end());