LeetCode算法题目:Sort List
来源:互联网 发布:淘宝详情页代码生成器 编辑:程序博客网 时间:2024/05/19 14:01
题目:
Sort a linked list in O(n log n) time using constant space complexity.
分析:
因为题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。
归并排序的一般步骤为:
将待排序数组(链表)取中点并一分为二;
递归地对左半部分进行归并排序;
递归地对右半部分进行归并排序;
将两个半部分进行合并(merge),得到结果。
所以对应此题目,可以划分为三个小问题:
找到链表中点 (快慢指针思路,快指针一次走两步,慢指针一次走一步,快指针在链表末尾时,慢指针恰好在链表中点);
写出merge函数,即如何合并链表。 (见merge-two-sorted-lists 一题解析)
写出mergesort函数,实现上述步骤。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* findMiddle(ListNode* head){ ListNode* chaser = head; ListNode* runner = head->next; while(runner != NULL && runner->next != NULL){ chaser = chaser->next; runner = runner->next->next; } return chaser; } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL){ return l2; } if(l2 == NULL){ return l1; } ListNode* dummy = new ListNode(0); ListNode* head = dummy; while(l1 != NULL && l2 != NULL){ if(l1->val > l2->val){ head->next = l2; l2 = l2->next; } else{ head->next = l1; l1 = l1->next; } head = head->next; } if(l1 == NULL){ head ->next = l2; } if(l2 == NULL){ head->next = l1; } return dummy->next; } ListNode* sortList(ListNode* head) { if(head == NULL || head ->next == NULL) return head; ListNode* middle = findMiddle(head); ListNode* right = sortList(middle->next); middle -> next = NULL; ListNode* left = sortList(head); return mergeTwoLists(left, right); }};
1 0
- LeetCode算法题目:Sort List
- LeetCode题目4:Sort List
- LeetCode算法题目:Sort Colors
- leetcode题目解答---Insertion Sort List
- LeetCode题目5:Insertion Sort List
- LeetCode算法题目:Partition List
- LeetCode算法题目:Rotate List
- leetcode 147 Insertion Sort List java 算法
- [leetcode][list][sort] Sort List
- leetcode做题总结,题目Sort List 2013/11/16
- LeetCode OJ平台上Sort Colors题目算法探讨
- leetcode题解-链表排序算法 147. Insertion Sort List && 148 . Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- Nginx学习-1( 支持PHP程序)
- 配置windows update失败还原更改_解决方案
- android stuid 取消svn 的关联
- 1. Two Sum
- Visual Studio 2017 vs2017安装 体验
- LeetCode算法题目:Sort List
- linux学习
- CSS content换行技术实现字符animation loading效果
- 利用条件随机场模型进行中文分词
- 不正经运维狗的文档2_11
- MySQL5.7.14-下载安装教程-->MySQL数据库语句详细教程
- 使用jQuery和java验证手机号码或者电话号码
- bind apply call
- PyMC3