148. Sort List -- 时间复杂度O(n log n)
2016-08-20 21:15
323 查看
Sort a linked list in O(n log n) time using constant space complexity.
归并排序
归并排序
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *sortList(ListNode *head) { if (head==NULL || head->next == NULL){ return head; } //find the middle place ListNode *p1=head, *p2=head->next; while(p2 && p2->next){ p1 = p1->next; p2 = p2->next->next; } p2 = p1->next; p1->next = NULL; return mergeTwoLists(sortList(head), sortList(p2)); } ListNode *mergeTwoLists(ListNode* head1, ListNode* head2){ ListNode *p1 = head1, *p2=head2; static ListNode dummy(0); ListNode *tail = &dummy; while(p1 && p2){ if(p1->val < p2->val){ tail->next = p1; p1 = p1->next; }else{ tail->next = p2; p2 = p2->next; } tail = tail->next; } if (p1) tail->next = p1; if (p2) tail->next = p2; return dummy.next; }
相关文章推荐
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- LeetCode-Sort List,链表排序(插入和归并),时间复杂度O(n^2) and O(nlgn)
- SkipList时间复杂度分析O(log n)
- java collection.sort()根据时间排序list
- hdu 4286 (list的reverse时间复杂度为n)
- android collection.sort()根据时间排序list
- <LeetCode OJ> 148. Sort List
- 148. Sort List (List)
- 求n^m 时间复杂度log(m)的算法
- 148. Sort List
- [LeetCode]148.Sort List
- [leetcode] 148. Sort List 解题报告
- leetcode Sort List (Sort a linked list in O(n log n) time using constant space complexity)
- leetcode_Sort a linked list in O(n log n) time using constant space complexity.
- java collection.sort()根据时间排序list
- 148. Sort List
- 继承List<T>类,并且完成List的Add()(在集合的末尾添加)方法和Get()(通过索引的方式获取)方法。并且写出方法的时间复杂度。
- 堆处理海量数据----求前k个最小的数--时间复杂度(n * log k)
- 快速排序时间复杂度为O(n×log(n))的证明
- 【Leet Code】148. Sort List---Medium