用于查找数组的独特成员的算法

Algorithm for finding unique members of array

本文关键字:成员 算法 数组 用于 查找      更新时间:2023-10-16

我需要写一个简单的算法:

  1. 查找排序数组的独特成员
  2. 将这些成员放到另一个数组
  3. 计数唯一成员的数量

这是一个示例:

char array1[103] = {'V', 'U', 'A', 'A', 'U', 'U', 'A', 'A', 'V', 'U', 'A', 'V', 'V', 'U', 'U'};
char array2[10]; //Empty
//Output should be:
3
V U A

我需要在C 中写下它,但是PSEUODO代码也很棒。我可以自己编写代码,我只需要了解此算法。

  1. 创建一个空的std::unordered_set对象。一套是只有独特元素的集合。
  2. 循环通过输入数组,将元素添加到集合中。
  3. 完成后,将集合的元素复制到输出数组中。

以下可能会有所帮助:

#include <cassert>
#include <cstring>
#include <algorithm>
#include <iostream>
int main(int argc, char *argv[])
{
    char array1[103] = {'V', 'U', 'A', 'A', 'U', 'U', 'A', 'A', 'V', 'U', 'A', 'V', 'V', 'U', 'U'};
    char array2[10]; //Empty
    int size = strlen(array1); // get the used size of the array
    std::sort(std::begin(array1), array1 + size);
    auto it = std::unique(std::begin(array1), array1 + size);
    size = it - std::begin(array1);
    assert(size < 10);
    std::copy(std::begin(array1), it, std::begin(array2));
    std::cout << size << std::endl;
    for (int i = 0; i != size; ++i) {
        std::cout << array2[i] << " ";
    }
    // Output is:
    //3
    //A U V
    return 0;
}