集合比较

数组和集合 / 集合(Set)

//C 没有集合:这是一个不含重复项的有序数组,
//所以查找就是二分查找
typedef struct {
    int *items;
    size_t count;
} Set;

int compareInts(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

//指向该元素的指针,没有这个元素时为 nullptr
int *setFind(const Set *s, int value) {
    return bsearch(&value, s->items, s->count, sizeof(int), compareInts);
}

//把值放到有序数组中的正确位置,重复项会被跳过
void setAdd(Set *s, int value) {
    if (setFind(s, value) != nullptr) {
        return;
    }
    s->items = realloc(s->items, (s->count + 1) * sizeof(int));
    size_t i = s->count;
    for (; i > 0 && s->items[i - 1] > value; i--) {
        s->items[i] = s->items[i - 1];
    }
    s->items[i] = value;
    s->count++;
}

Set first = {};
setAdd(&first, 1);
setAdd(&first, 2);
Set second = {};
setAdd(&second, 2);
setAdd(&second, 1);
Set third = {};
setAdd(&third, 1);
setAdd(&third, 2);
setAdd(&third, 3);

//两个数组都有序,所以相等的集合数组也相等
bool isEqual = first.count == second.count
    && memcmp(first.items, second.items, first.count * sizeof(int)) == 0;
//isEqual is true

//first 的某个元素在 third 中
bool isIntersects = false;
for (size_t i = 0; i < first.count && !isIntersects; i++) {
    isIntersects = setFind(&third, first.items[i]) != nullptr;
}
//isIntersects is true

//third 的每个元素都在 first 中
bool isSubset = true;
for (size_t i = 0; i < third.count && isSubset; i++) {
    isSubset = setFind(&first, third.items[i]) != nullptr;
}
//isSubset is false

printf("isEqual is %s\n", isEqual ? "true" : "false");
printf("isIntersects is %s\n", isIntersects ? "true" : "false");
printf("isSubset is %s\n", isSubset ? "true" : "false");
free(first.items);
free(second.items);
free(third.items);