2018年10月17日 星期三

[LeetCode] 23. merge k sorted lists


  • Problems: merge k 個 sorted 的 lists
  • Solution:
  • /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeLists(ListNode *l1, ListNode *l2)
        {
            // ref to problem 22, merge two sorted list
            if (NULL == l1) return l2;
            if (NULL == l2) return l1;
            
            if (l1->val < l2->val) {
                l1->next = mergeLists(l1->next, l2);
                return l1;
            } else {
                l2->next = mergeLists(l1, l2->next);
                return l2;
            }
        }
    
        ListNode* mergeKLists(vector& lists) {
            // merge 2 by 2 lists
            size_t iters = lists.size() / 2;
            while (iters > 0) {
                iters = lists.size() / 2;
                for (size_t i = 0; i < iters; i++){
                    lists[i] = mergeLists(lists[i], lists[lists.size() - 1 - i]);
                }
    
                lists.erase(lists.begin() + iters + (1 == lists.size() % 2), lists.end());
            }
            return (lists.size() > 0) ? lists[0] : NULL;
        }
    };
    

沒有留言:

張貼留言