Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

第一次尝试,思路:想象有n列个向量,每当要merge的时候,比较每一列的第一个大小,取下最小的那个节点返回并且将该节点从当前向量中剔除(search函数来完成)。当search函数返回NULL 的时候说明所有的node都被遍历了一边,所以标志着结束。

但是这个算法的复杂度比较高。假设有n个数字,每个数字在被取走之前都会被遍历一次,所以第x大的数字会被遍历x次的,所以复杂度O(n^2)

提醒超时TLE

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* search(struct ListNode** lists, int size);

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
    struct ListNode *head,*forward,*next;
    head=(struct ListNode*)malloc(sizeof(struct ListNode));
    head->next=NULL;
    forward=head;
    while((next=search(lists,listsSize))!=NULL){
        forward->next=next;
        forward=next;
    }
    //next=NULL,no Node any more;
    //no need to add the terminated NULL,cause the last node must\
    //terminate with a NULL;
    //forward->next=next;
    forward=head;
    head=forward->next;
    free(forward);
    return head;
    
}

struct ListNode* search(struct ListNode** lists, int size){
    struct ListNode* temp=*lists;
    size_t i=0;
    int ptr;
    for(;i!=size;i++){
        if(temp==NULL) temp=*(lists+i);
        else if((*(lists+i)!=NULL)&&((*(lists+i))->val)<(temp->val)) {
            temp=*(lists+i);//temp save the pointer to smallest val
            ptr=i;
        }
    }
    if(temp==NULL) return NULL;
    *(lists+ptr)=temp->next;
    return temp;
    
}

第二次尝试:为降低复杂度,牺牲存储。将所有的链表的值复制到数组中,利用stdlib中的qsort快排达到nlogn的复杂度。

代码如下,依旧提醒超时。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
int cmp(const void *a, const void *b)
{
    return *(int*)a - *(int*)b; //由小到大排序
    //return *(int *)b - *(int *)a; 由大到小排序
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
    struct ListNode*temp=*lists;
    int array[1000];
    int size=0;  //indicate the size of array
    for(int i=0;i<listsSize;i++)
    {
        struct ListNode*temp=*(lists+i);
        while(temp!=NULL){
            array[size++]=temp->val;
            temp=temp->next;
        }
    }
    if(size==0) return 0;
    qsort(array,size,sizeof(int),cmp);
    struct ListNode* head=(struct ListNode*)malloc(size*sizeof(struct ListNode));
    temp=head;
    int i=0;
    while(i<size){
        temp->val=array[i];
        if(i!=size-1) {
            temp->next=temp+1;
            temp=temp->next;
        }
    }
    temp->next=NULL;
    return head;
    
}

第三次尝试:

=====================分割线==============

下次再写

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值