c++ - C/C++ 如何从 2 个数组中获取唯一值?

标签 c++ c arrays unique

我需要从 2 个 int 数组中获取唯一值

允许重复

只有一个唯一值

喜欢:

int arr1[3]={1,2,3};
int arr2[3]={2,2,3};

我想得到的值是:

int unique[]={1}

我该怎么做? 我已经对我的“for”和“if”感到困惑 这不是作业

我知道如何合并 2 个数组并删除重复值

但我还需要知道哪个数组具有唯一值

请帮助我:)

这是我做的一些代码

int arr1[3]={1,2,3}
int arr2[3]={2,2,3}
int arrunique[1];
bool unique = true;
for (int i=0;i!=3;i++)
{

    for (int j=0;j!=3;j++)
    {
    if(arr1[i]==arr2[j])
    {
        unique=false;
        continue;
    }
    else 
    {
        unique=true;
    }
if(unique)
{
arrunique[0]=arr1[i]
break;
}
}

cout << arrunique[0];

最佳答案

假设:

  • 你有两个不同长度的数组,
  • 数组已排序
  • 数组中可以有重复的值
  • 您想获取仅出现在其中一个数组中的值列表
    • 包括它们的拷贝(如果存在的话)

你可以这样做(未经测试):

// Assuming arr1[], arr2[], and lengths as arr1_length  
int i = 0,j = 0, k = 0;
int unique[arr1_length + arr2_length];

while(i < arr1_length && j < arr2_length) {
   if(arr1[i] == arr2[j]) {
     // skip all occurrences of this number in both lists
     int temp = arr1[i];
     while(i < arr1_length && arr1[i] == temp) i++;
     while(j < arr2_length && arr2[j] == temp) j++;
   } else if(arr1[i] > arr2[j]) {
     // the lower number only occurs in arr2
     unique[k++] = arr2[j++]; 
   } else if(arr2[j] > arr1[i]) {
     // the lower number only occurs in arr1
     unique[k++] = arr1[i++]; 
   }     
}

while(i < arr1_length) {
   // if there are numbers still to read in arr1, they're all unique
   unique[k++] = arr1[i++];
}
while(j < arr2_length) {
   // if there are numbers still to read in arr2, they're all unique
   unique[k++] = arr2[j++];
}

一些备选方案:

  • 如果您不希望 unique 数组中出现重复项,那么您可以在分配给 unique 数组时跳过相关列表中所有出现该数字的地方。

  • 如果要记录位置而不是值,则维护两个“唯一位置”数组(每个输入数组一个)并分配 ij 到相应的数组。

  • 如果只有一个唯一值,将赋值改为唯一数组返回。

关于c++ - C/C++ 如何从 2 个数组中获取唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10326928/

相关文章:

c++ - 使用自定义比较器返回 std::set

c - C中两个数组的交集函数

c - 试图在 C 中交换字符串?

php不需要属性吗?

c++ - 如何访问新的 c++11 标准大小的类型?

c++ - 为什么只执行最后一个线程?

JavaScript 函数不检索数组元素

c - 在 C 中给定开始和结束内存地址的意外行为遍历数组

c++ - 尝试使用模式为 "a+"的 fwrite() 将新文本附加到现有文件,但写入了奇怪的字符串

c - 如何让 C 编译器假定十进制文字(例如 1.23)是 float 而不是 double ?