【leetcode】23合併k個有序鏈表

題目描述:

leetcode23

思路:

代碼實現:

/**
 * 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.empty())  return NULL;
       int n = lists.size();
       while(n > 1){
           int k = (n + 1)/2;
           for(int i = 0; i < n / 2; i++){//分別合併n/2次
               lists[i] = helper(lists[i],lists[i+k]);
           }
           n = k;//繼續下一次合併
       }  
       return lists[0];
    }

    ListNode* helper(ListNode* l1, ListNode* l2){
        ListNode* dummy = new ListNode(-1), *cur = dummy;
        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 dummy->next;
    }
};
 class Compare{
public://【注意這裏必須寫成public】
     bool operator()(ListNode* l1, ListNode*l2){
         return l1->val > l2->val;
     }

 };
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>,Compare> q;

        for(auto i : lists){
            if(i)  q.push(i);
        }

        ListNode* dummy = new ListNode(-1), *cur = dummy;
        while(!q.empty()){
            auto t = q.top();
            q.pop();

            cur->next = t;
            cur = cur->next;
            if(cur->next) q.push(cur->next);
        }
        return dummy->next;
    }
};

參考:https://blog.csdn.net/zlasd/article/details/52605601

參考:https://www.cnblogs.com/grandyang/p/4606710.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章