题解 | #有序序列合并#

有序序列合并

https://www.nowcoder.com/practice/a9e943b0dab142759807d0cfb6863897

#include <stdio.h>
#include <stdlib.h>
int main() {
    int a, b;
    while (scanf("%d %d", &a, &b) != EOF) {
        int* arr1 = (int*)malloc(sizeof(int) * a);
        int* arr2 = (int*)malloc(sizeof(int) * b);
        int* arr3 = (int*)malloc(sizeof(int) * (b + a));
        if (arr1 == NULL || arr2 == NULL || arr3 == NULL) {
            printf("内存分配失败\n");
            return -1;
        }
        int* p1 = arr1;
        int* p2 = arr2;
        int* p3 = arr3;

        for (int i = 0; i < a; i++)
            scanf("%d", (p1++));
        for (int i = 0; i < b; i++)
            scanf("%d", (p2++));

        p1 = arr1; // 重置指针位置
        p2 = arr2; // 重置指针位置

        while (p1 - arr1 < a && p2 - arr2 < b) {
            if (*p1 <= *p2)
                *(p3++) = *(p1++);
            else if (*p1 > *p2)
                *(p3++) = *(p2++);
        }

        while (p1 - arr1 < a)
            *(p3++) = *(p1++);

        while (p2 - arr2 < b)
            *(p3++) = *(p2++);
        p3 = arr3;
        for (int j = 0; j < a + b; j++)
            printf("%d ", *(p3++));
        free(arr1);
        free(arr2);
        free(arr3);
    }
    return 0;
}

全部评论

相关推荐

11-08 17:36
诺瓦科技_HR
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务