LeetCode算法题目:Merge k Sorted Lists

来源:互联网 发布:屏蔽按键软件 编辑:程序博客网 时间:2024/06/05 15:40

题目:

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


分析:

分治法 (Divide and Conquer Approach),简单来说就是不停的对半划分,比如k个链表先划分为合并两个k/2个链表的任务,再不停的往下划分,直到划分成只有一个或两个链表的任务,开始合并。


代码:

/** * 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) {        if (lists.size() == 0) return NULL;        int n = lists.size();        while (n > 1) {            int k = (n + 1) / 2;            for (int i = 0; i < n / 2; ++i) {                lists[i] = mergeTwoLists(lists[i], lists[i + k]);            }            n = k;        }        return lists[0];    }    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        ListNode *head = new ListNode(-1);        ListNode *cur = head;        while (l1 && l2) {            if (l1->val < l2->val) {                cur->next = l1;                l1 = l1->next;            } else {                cur->next = l2;                l2 = l2->next;            }            cur = cur->next;        }        if (l1) cur->next = l1;        if (l2) cur->next = l2;        return head->next;    }};
0 0