-3

我有一个二维整数表(全为正数),并希望制作一个所有整数只有一次的一维表,(无重复数字)已排序。二维中的每一行都已排序。

例子:

二维表

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
4

2 回答 2

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;
}
于 2013-04-12T10:33:36.400 回答
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;
}
于 2013-04-12T11:56:05.030 回答