leetcode-Merge k Sorted Lists-23(未完待续)
2016-06-09 17:05
295 查看
合并k个有序链表
每次合并相邻两个就行,直接用一趟归并排序的函数,时间k*max(length),空间ON,因为在一趟归并排序时要用一个单独的链表存储结果
网上说得最多的是用堆来做,以后完善
每次合并相邻两个就行,直接用一趟归并排序的函数,时间k*max(length),空间ON,因为在一趟归并排序时要用一个单独的链表存储结果
网上说得最多的是用堆来做,以后完善
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* merge(ListNode* l1,ListNode* l2){ if(l1==NULL) return l2; if(l2==NULL) return l1; ListNode* head=NULL; ListNode* tail=NULL; ListNode* p=l1; ListNode* q=l2; if(p->val <= q->val){ head=p; tail=p; p=p->next; tail->next=NULL; } else{ head=q; tail=q; q=q->next; tail->next=NULL; } while(p&&q){ if(p->val <= q->val){ tail->next=p; tail=p; p=p->next; tail->next=NULL; } else{ tail->next=q; tail=q; q=q->next; tail->next=NULL; } } if(p) tail->next=p; else tail->next=q; return head; } ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size()==0) return NULL; ListNode* head=lists[0]; for(int i=1;i<lists.size();i++){ head=merge(head,lists[i]); } return head; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解