an easy understanding c++ solution, 32ms


  • 0
    F
    /**
     * 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()) {
                return NULL;
            }
            int curSize = lists.size();
            int step = curSize / 2;
            while (curSize > 1) {
                for(int i = 0; i < step; ++i) {
                    lists[i] = mergeTwo(lists[i], lists[curSize - i - 1]);
                }
                curSize = (curSize + 1) / 2;
                step = curSize / 2;
            }
            return lists[0];
        }
        ListNode* mergeTwo(ListNode* l1, ListNode* l2) {
            ListNode head(0);
            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;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.