标签:des style blog color io 使用 ar for strong
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity
1. Naive Solution
思路:直接的想法依次找出列表中的最小项串接起来。 复杂度分析:时间复杂度:O(k*n), 空间复杂度:O(c)。其中 n为最长子列表长度,c为常量。
ListNode *mergeKLists(vector<ListNode *>&lists) { int n = (int) lists.size(); if (n == 0) return NULL; ListNode *p = new ListNode(0); ListNode *q = p; int empty = 0; int k; while (empty < n) { k = -1; int i; for (i = 0; i < n; ++i) { if (lists[i]) { k = i; break; } } for (int j = i + 1; j < n; ++j) { if (lists[j] && (lists[j]->val) < (lists[i]->val)) { k = j; } } if (k == -1) break; q->next = lists[k]; q = q->next; lists[k] = lists[k]->next; if (!q->next) ++empty; } q = p->next; delete p; return q; }
结果导致TLE,无法AC。
2. Advanced Solution
思路:使用Priority Queue。复杂度分析:时间复杂度O(lgk *n),空间复杂度O(k)。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { class MergeCompareFunc { public: typedef ListNode * ListNodeP; bool operator() (const ListNodeP & a, const ListNodeP & b) const {return (a->val > b->val);} }; public: ListNode *mergeKLists(vector<ListNode *> &lists) { if (lists.size() < 1) { return NULL; } priority_queue<ListNode*, vector<ListNode *>, MergeCompareFunc> pqueue; for (ListNode *node : lists) { if (node != NULL) { pqueue.push(node); } } ListNode *p = new ListNode(0); ListNode *q = p; while (pqueue.size() > 0) { ListNode *n = pqueue.top(); pqueue.pop(); q->next = n; q = q->next; if (n->next) pqueue.push(n->next); } q = p->next; delete p; return q; } };
可以AC。
LeetCode: Merge k Sorted Lists
标签:des style blog color io 使用 ar for strong
原文地址:http://www.cnblogs.com/liew/p/4003719.html