在c中有整数的表的联合合并

时间:2013-04-12 10:15:28

标签: c

我有一个2-d整数表(全部为正),并且想要制作一个只有一次所有整数的1-d表,(没有重复的数字)已排序.2-d中的每一行已经排序

示例:

2-d表

15 20 40 69 74 83

12 40 58 74 82 94 111

19 30 69

12 19

44 64 74 83

答案: 一维表:

12, 15, 19, 20, 30, 40, 44, 58, 64, 69, 74, 82, 83, 94, 111

2 个答案:

答案 0 :(得分:1)

#include <stdio.h>

int main() {
    int subtable1[] = {15, 20, 40, 69, 74, 83, 0};
    int subtable2[] = {12, 40, 58, 74, 82, 94, 111, 0};
    int subtable3[] = {19, 30, 69, 0};
    int subtable4[] = {12, 19, 0};
    int subtable5[] = {44, 64, 74, 83, 0};
    int *table[] = { subtable1, subtable2, subtable3, subtable4, subtable5};
    int result[128] = {0};
    int temp[128] = {0};
    int i,j, count=0;

    for(i=0;i<sizeof(table)/sizeof(int*);++i)
        for(j=0;table[i][j];++j)
            ++temp[table[i][j]];

    for(i=1;i<128;++i)
        if(temp[i])
            result[count++]=i;
    //check print
    for(i=0;i<count;++i)
        printf("%d ", result[i]);
    printf("\n");

    return 0;
}

答案 1 :(得分:0)

另一种方式

#include <stdio.h>
#include <stdlib.h>

int* merge(int* array1, int* array2){
    int *result = NULL;
    int size=0;

    result = (int*)malloc(sizeof(int)*48);//need capacity check!
    while(*array1 || *array2){
        if(*array1 && *array2){
            if(*array1 < *array2){
                result[size++]=*array1++;
                continue;
            }
            if(*array1 > *array2){
                result[size++]=*array2++;
                continue;
            }
            if(*array1 == *array2){
                result[size++]=*array1++;
                array2++;
                continue;
            }
        }
        if(*array1){
            while(*array1)
                result[size++]=*array1++;
        }
        if(*array2){
            while(*array2)
                result[size++]=*array2++;
        }
    }
    result[size++]=0;
    result = realloc(result, sizeof(int)*size);
    return result;
}

int main() {
    int subtable1[] = {15, 20, 40, 69, 74, 83, 0};
    int subtable2[] = {12, 40, 58, 74, 82, 94, 111, 0};
    int subtable3[] = {19, 30, 69, 0};
    int subtable4[] = {12, 19, 0};
    int subtable5[] = {44, 64, 74, 83, 0};
//  int *table[] = { subtable1, subtable2, subtable3, subtable4, subtable5 };
    int *m12, *m34, *m1234, *result;
    int counter=0;

    m12=merge(subtable1, subtable2);
    m34=merge(subtable3, subtable4);
    m1234=merge(m12, m34);
    result=merge(m1234, subtable5);
    //check print
    for(counter=0;result[counter];++counter)
        printf("%d ", result[counter]);
    printf("\n");
    //need free
    return 0;
}