Merge k Sorted Lists

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

两个方法: 方法1. 利用 STL 中的 multiset (根据结点内的值)自动对指针排序。空间 O(N), 时间 O(NlogN).

(亦可用于 k 个无序链表)。(AC: 164ms

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool compare (const ListNode *p1, const ListNode *p2) {
return p1->val < p2->val;
}
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
typedef bool (*cmp) (const ListNode *p1, const ListNode *p2);
multiset<ListNode*, cmp> container(compare);
for(size_t i = 0; i < lists.size(); ++i) {
ListNode *p = lists[i];
while(p) { container.insert(p); p = p->next; }
}
ListNode *head = NULL, *p = head;
for(auto it = container.begin(); it != container.end(); ++it) {
if(p) { p->next = *it; p = *it; }
else p = head = *it;
}
if(p) p->next = NULL;
return head;
}
};

方法2. 不利用任何 STL 函数。对指针建堆排序,只需要一个(win32: 4Byte)指针数组即可。空间 : O(K), 时间 O(NlogK)

(AC: 140ms)

最初代码:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
heap = vector<ListNode*>(lists.size(), );
sz = ;
for(size_t i = ; i < lists.size(); ++i)
if(lists[i]) push(lists[i]);
ListNode *head = NULL, *p = head;
while(sz) {
if(head == NULL)
p = head = pop();
else {
p->next = pop();
p = p->next;
}
if(p->next) push(p->next);
}
return head;
}
void push(ListNode *p) {
int child = sz++;
while(child > ) {
int father = (child-) / ;
if(p->val >= heap[father]->val) break;
heap[child] = heap[father];
child = father;
}
heap[child] = p;
}
ListNode* pop() {
ListNode *pAns = heap[];
heap[] = heap[--sz];
int father = , child = ;
ListNode *p = heap[father];
while(child < sz) {
if(child+ < sz && heap[child]->val > heap[child+]->val) ++child;
if(heap[child]->val >= p->val) break;
heap[father] = heap[child];
father = child;
child = * father + ;
}
heap[father] = p;
return pAns;
}
private:
int sz;
vector<ListNode*> heap;
};

优化后(增强易读性):

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Heap {
public:
Heap(size_t n) : sz(0), heap(vector<ListNode*>(n, NULL)) {}
void push(ListNode *p);
ListNode* pop();
int size() { return sz; }
private:
int sz;
vector<ListNode*> heap;
};
inline void Heap::push(ListNode *p) {
int child = sz++;
while(child > 0) {
int father = (child-1) / 2;
if(p->val >= heap[father]->val) break;
heap[child] = heap[father];
child = father;
}
heap[child] = p;
}
inline ListNode* Heap::pop() {
ListNode *pAns = heap[0];
heap[0] = heap[--sz];
int father = 0, child = 1;
ListNode *p = heap[father];
while(child < sz) {
if(child+1 < sz && heap[child]->val > heap[child+1]->val) ++child;
if(heap[child]->val >= p->val) break;
heap[father] = heap[child];
father = child;
child = 2 * father + 1;
}
heap[father] = p;
return pAns;
}
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
Heap heap(lists.size());
for(size_t i = 0; i < lists.size(); ++i)
if(lists[i]) heap.push(lists[i]);
ListNode *head = NULL, *p = head;
while(heap.size()) {
if(head == NULL)
p = head = heap.pop();
else {
p->next = heap.pop();
p = p->next;
}
if(p->next) heap.push(p->next);
}
return head;
}
};

71. Merge k Sorted Lists的更多相关文章

  1. Merge k Sorted Lists

    1. Merge Two Sorted Lists 我们先来看这个 问题: Merge two sorted linked lists and return it as a new list. The ...

  2. 【leetcode】Merge k Sorted Lists

    Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...

  3. 【LeetCode练习题】Merge k Sorted Lists

    Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...

  4. [Leetcode][Python]23: Merge k Sorted Lists

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 23: Merge k Sorted Listshttps://oj.leet ...

  5. LeetCode之“链表”:Merge Two Sorted Lists && Merge k Sorted Lists

    1. Merge Two Sorted Lists 题目链接 题目要求:  Merge two sorted linked lists and return it as a new list. The ...

  6. leetcode-algorithms-23 Merge k Sorted Lists

    leetcode-algorithms-23 Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted ...

  7. python 中的堆 (heapq 模块)应用:Merge K Sorted Lists

    堆是计算机科学中一类特殊的数据结构的统称.堆通常是一个可以被看做一棵树的数组对象.在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短 ...

  8. 蜗牛慢慢爬 LeetCode 23. Merge k Sorted Lists [Difficulty: Hard]

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

  9. LeetCode: Merge k Sorted Lists 解题报告

    Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...

随机推荐

  1. C#编程语言与面向对象——委托

    委托(delegate)也可以看成是一种数据类型,可以用于定义变量,但它是一种特殊的数据类型,所定义的变量能接收的数值只能是个函数,更确切地说,委托类型的变量可以接收一个函数的地址. 简单地说 委托变 ...

  2. 最短路径问题——floyd算法

    floyd算法和之前讲的bellman算法.dijkstra算法最大的不同在于它所处理的终于不再是单源问题了,floyd可以解决任何点到点之间的最短路径问题,个人觉得floyd是最简单最好用的一种算法 ...

  3. FTP弱口令猜解【python脚本】

    ftp弱口令猜解 python脚本: #! /usr/bin/env python # _*_ coding:utf-8 _*_ import ftplib,time username_list=[' ...

  4. 通过js的console优雅的将php调试信息输出

    function consoleLog($val){ $debug = debug_backtrace(); unset($debug[0]['args']); echo '<script> ...

  5. Examples of complexity pattern

    O(1):constant - the operation doesn't depend on the size of its input, e.g. adding a node to the tai ...

  6. org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection 原因

    org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection 可能出现的原因     ...

  7. 第一次在linux上登录博客

    这是我第一次在linux操作系统上登录博客,额,虽然是在X-window上面.好吧,是我太激动了. 这意味着我已经步入linux的世界了,虽然中文输入法不太好用,但是我还是写一下我的心情吧. 从去年的 ...

  8. ftplib模块

    Python中的ftplib模块 Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件 FTP的工作流程及基本操作可参考协议RFC95 ...

  9. docker-centos 7.2

    1.安装准备 预防volumes项出现Permission denied setenforce 0 #关闭selinux防火墙,临时关闭.永久关闭需改/etc/selinux/config文件,将SE ...

  10. Imagenet tools install on windows

    1.find the pyrcc4.exe path: C:\Anaconda2\Library\bin 2.cmd: pyrcc4 -o resources.py resources.qrc 3.a ...