408ms Easy C++ Solutions


  • 0

    Well, the idea of this problem is actually very sample --- keep merging the unmerged lists in lists until there is exactly one list remained. However, do not merge lists[0] with lists[1], lists[2], ..., lists[n - 1] sequentially since that will cause TLE. You may merge the first two lists and then push it back to lists and erase the first two to avoid repeated merging, or use some variables to control the merging process, as the following code.

    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            if (lists.empty()) return NULL;
            int n = lists.size();
            while (n > 1) {
                for (int i = 0; i < n / 2; i++)
                    lists[i] = mergeLists(lists[i], lists[n - 1 - i]);
                n = (n + 1) / 2;
            }
            return lists[0];
        } 
    private:
        ListNode* mergeLists(ListNode* head1, ListNode* head2) {
            ListNode* new_head = new ListNode(0);
            ListNode* run = new_head;
            ListNode* run1 = head1;
            ListNode* run2 = head2;
            while (run1 && run2) {
                if (run1 -> val <= run2 -> val) {
                    run -> next = run1;
                    run1 = run1 -> next;
                }
                else {
                    run -> next = run2;
                    run2 = run2 -> next;
                }
                run = run -> next;
            }
            run -> next = run1 ? run1 : run2;
            return new_head -> next;
        }
    };

Log in to reply
 

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