合并k个有序链表 Merge k Sorted Lists

题目源自于leetcode。

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

解法一:每次在各个有序链表中寻找的表头寻找出最小的一个结点,将其链到新链表上。空间复杂度为O(1),时间复杂度为O(k*n),k为有序链表的个数,n为每个链表的长度。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector &lists) {
        int n = lists.size();
        ListNode *result, *p;
        
        int j;
        int min_idx;
        int min_value = INT_MAX;
        for(j=0;jval < min_value)
            {
                min_value = lists[j]->val;
                min_idx = j;
            }
        }
        if(min_value == INT_MAX)
            return NULL;
        result = lists[min_idx];
        lists[min_idx] = lists[min_idx]->next;
        p = result;
        p->next = NULL;
        
        while(true)
        {
            min_value = INT_MAX;
            for(j=0;jval < min_value)
                {
                    min_value = lists[j]->val;
                    min_idx = j;
                }
            }
            if(min_value == INT_MAX)
                break;
            p->next = lists[min_idx];
            lists[min_idx] = lists[min_idx]->next;
            p = p->next;
            p->next = NULL;
            
        }
        return result;
    }
};


解法二:每次都是两两合并,合并之后再拿新的过来合并。其中两两合并的函数和两个有序链表的合并 Merge Two Sorted Lists中是一样的。方法二的时空复杂度和方法一是一致的。

class Solution {
public:
    ListNode *mergeKLists(vector &lists) {
        if(lists.empty())
            return NULL;
        int n = lists.size();
        ListNode *p = lists[0];
        for(int i=1;ival < l2->val)
            {
                p->next = l1;
                l1 = l1->next;
            }
            else
            {
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if(l1 == NULL)
            p->next = l2;
        else
            p->next = l1;
        return tmp.next;
    }
};

你可能感兴趣的:(LeetCode,链式结构问题,我爱算法)