leetcode 合并K个排序链表 (c++实现)

  这道题耗时40ms,思路是联想到快慢指针,vector有几个元素,我也有几个头指针,若A的头指针最小,就放入结果指针head的next中,则A就比别的指针快一步,移到下一位next。问题就是判断如何最小,可以自己写,也可以使用priority_queue这样有序的数据结构。感谢博客最下面的链接,我也学到了如何自定义比较器。代码如下:

struct cmp {
    bool operator()(ListNode *&a, ListNode *&b) const {
        return a->val > b->val;
    }
};
class Solution {
public:
    ListNode* mergeKLists(vector& lists) {
        if (lists.size() == 0) return nullptr;
        priority_queue, cmp> q;
        for (int i = 0; i < lists.size(); ++i) {
            if (lists[i] != NULL) {
                q.push(lists[i]);
            }
        }
        ListNode* head = new ListNode(0);
        ListNode* tail = head;
        while (!q.empty()) {
            tail->next = q.top();
            q.pop();
            tail = tail->next;
            if (tail->next != NULL) {
                q.push(tail->next);
            }            
        }
        return head->next;
    }
};

  最快实现代码如下,运用两个链表合并的方式:

class Solution {
public:
    ListNode* mergeKLists(vector& lists) {
        if (lists.empty())
            return NULL;
        int len = lists.size();
        while (len > 1) {
            for (int i = 0; i < len / 2; ++i) {
                lists[i] = mergeTwoLists(lists[i], lists[len - 1 - i]);
            }
            len = (len + 1) / 2;
        }
        return lists[0];
    }
    
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *head = new ListNode(0);
        ListNode *p = head;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                p->next = l1;
                p = l1;
                l1 = l1->next;
            }
            else {
                p->next = l2;
                p = l2;
                l2 = l2->next;
            }
        }
        if (l1)
            p->next = l1;
        else if (l2)
            p->next = l2;
         return head->next;
    }
};
引用与感谢
  • https://blog.csdn.net/m0_38015368/article/details/80461938

你可能感兴趣的:(leetcode)