题解 | #合并表记录#

合并表记录

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

#include <stdio.h>

struct node {
    int index;
    int value;
    struct node* next;
};
int main() {
    int n;
    struct node* header = (struct node*) calloc(sizeof(struct node), 1);

    int index, value;
    scanf("%d", &n);

    for (int i = 0 ; i < n; i++) {
        scanf("%d %d", &index, &value);
        if (header->next == NULL) {
            struct node* indexNode = (struct node*) calloc(sizeof(struct node), 1);
            header->next = indexNode;
            indexNode->index = index;
            indexNode->value = value;
        } else {
            struct node* p = header;
            while (p != NULL) {
                if (p->next == NULL) {
                    struct node* new = (struct node*) calloc(sizeof(struct node), 1);
                    new->next = p->next;
                    p->next = new;
                    new->index = index;
                    new->value = value;
                    break;
                } else if (p->next->index >= index) {
                    if (p->next->index == index) {
                        p->next->value += value;
                    } else {
                        struct node* new = (struct node*) calloc(sizeof(struct node), 1);
                        new->next = p->next;
                        p->next = new;
                        new->index = index;
                        new->value = value;
                    }
                    break;
                } else   {
                    p = p->next;
                }

            }
        }
    }

    struct node* p = header;
    while(p->next != NULL){
        printf("%d %d\n", p->next->index, p->next->value);
        p = p->next;
    }

    return 0;
}

我以为这样实现复杂度会小一点,还是低估了,不过这样内存占用应该是最小的了

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-21 17:16
科大讯飞 算法工程师 28.0k*14.0, 百分之三十是绩效,惯例只发0.9
点赞 评论 收藏
分享
面试摇了我吧:啊哈哈面试提前五个小时发,点击不能参加就是放弃
点赞 评论 收藏
分享
三年之期已到我的offer快到碗里来:9硕都比不上9本
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务