c++ - 如何在 O(n) 运行时间内从答案中删除重复项?

标签 c++ hash time-complexity duplicates

void findodd(int a[])
{
  int hash[100];
  int i;
  int c[100]={0};
  for(i=0;i<6;i++)
  { 
    c[a[i]]=c[a[i]]+1;
    hash[a[i]]=c[a[i]];
    if(c[a[i]]%2==0)
      hash[a[i]]=0;
  }
  for(i=0;i<6;i++)
    if(hash[a[i]]!=0)
      cout<<a[i];
}
int main()
{
  int a[] = {1,3,3,5,5,5};
  findodd(a);
  return 0;
}

该程序是找出数组中出现奇数次的整数。这是link到上面的程序。

最佳答案

鉴于您的算法已经在 O(n) 上运行,我假设您希望删除输出中的重复条目。一种可能的解决方案是:

void findodd(int a[])
{
  int hash[100];
  int i;
  int c[100]={0};

  int hashdup[100];
  memset(hashdup, 0, sizeof(int)*100);

  for(i=0;i<6;i++)
  { 
    c[a[i]]=c[a[i]]+1;
    hash[a[i]]=c[a[i]];
    if(c[a[i]]%2==0)
      hash[a[i]]=0;
  }
  for(i=0;i<6;i++)
  {
    if(hash[a[i]]!=0)
      hashdup[a[i]]++;
    if (hashdup[a[i]]==1)
      cout<<a[i];
  }
}

关于c++ - 如何在 O(n) 运行时间内从答案中删除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5292299/

相关文章:

python - 转换整数数组并计算总和

algorithm - i^k 的循环复杂度

python - 说这个算法是 O(n+m) 正确吗?

c++ - 根据运行时参数调用不同版本的模板函数

C++ 创建一个函数来读取 .txt 文件并检查以确保文件存在,但我的循环不工作

node.js - 每次服务器重新启动时散列模式都会更改

javascript - URL 更改不会重新加载文档 -> 如何检查哈希值?

php mysqli_connect : authentication method unknown to the client [caching_sha2_password]

c++ - 为什么在构造函数中分配器?

c++ - 使用原始类型进行模乘的方法