LeetCode——merge-k-sorted-lists

Question

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

Solution

  1. 归并排序中的Merge过程。

  2. 时间复杂度: 节点数目*k

Code

/**
 * 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) {
        int size = lists.size();
        if (size == 0)
            return NULL;
        if (size == 1)
            return lists[0];
        ListNode* head = new ListNode(-1);
        ListNode* pNode = head;
        while (1) {
            bool flag = false;
            int index;
            int cur = INT_MAX;
            for (int i = 0; i < size; i++) {
                if (lists[i] != NULL) {
                    flag = true;
                    if (lists[i]->val < cur) {
                        cur = lists[i]->val;
                        index = i;
                    }
                }
            }
            if (flag == false)
                break;
            pNode->next = lists[index];
            pNode = lists[index];
            lists[index] = lists[index]->next;
        }
        return head->next;
    }
};
posted @ 2017-11-01 15:21  清水汪汪  阅读(116)  评论(0编辑  收藏  举报