zoukankan      html  css  js  c++  java
  • [itint5]合并K个有序链表

    merge sort,leet code里面曾经做过。但一开始没这么写,遍历来做,效率n*k了,用了merge sort后,变成logn*k。

    用了dummy node。同时要注意size为0的情况。

    #include <climits>
    
    /*链表结点的定义(请不要在代码中定义该类型)
    struct ListNode {
      int val;
      ListNode *next;
    };
    */
    //lists包含k个链表的头结点,返回合并后链表头结点
    ListNode* merge(vector<ListNode*> &lists) {
        if (lists.size() == 0) return NULL;
        int k = 1;
        while (k < lists.size()) {
            for (int i = 0; i < lists.size(); i += k*2) {
                int j = i + k;
                if (j >= lists.size()) break;
                // merge list i and j
                ListNode *dummy = new ListNode();
                ListNode *last = dummy;
                while (lists[i] != NULL && lists[j] != NULL) {
                    if (lists[i]->val < lists[j]->val) {
                        last->next = lists[i];
                        last = last->next;
                        lists[i] = lists[i]->next;
                    } else {
                        last->next = lists[j];
                        last = last->next;
                        lists[j] = lists[j]->next;
                    }
                }
                while (lists[i] != NULL) {
                    last->next = lists[i];
                    last = last->next;
                    lists[i] = lists[i]->next;
                }
                while (lists[j] != NULL) {
                    last->next = lists[j];
                    last = last->next;
                    lists[j] = lists[j]->next;
                }
                last->next = NULL;
                lists[i] = dummy->next;
                delete dummy;
            }
            k *= 2;
        }
        return lists[0];
    }
    

      

  • 相关阅读:
    进程与线程
    linux网关服务器
    linux硬盘分区和fdisk命令
    MyISAM与InnoDB两者之间区别与选择(转)
    系统吞吐量与QPS/TPS
    linux最大打开文件句柄数
    内存性能测试 Memtester+mbw
    硬盘性能测试
    使用JNA访问WindowsAPI操作Windows窗口元素
    [博客页面装饰]----[人体时钟]插件
  • 原文地址:https://www.cnblogs.com/lautsie/p/3525821.html
Copyright © 2011-2022 走看看