leetcode第一刷_Sort List
来源:互联网 发布:淘宝客服兼职多少钱 编辑:程序博客网 时间:2024/05/01 19:19
这道题其实是道数据结构的题,跟链表相关的问题一般都比较直接,但是比较麻烦。
排序嘛,大家都知道最好的平均复杂度就是O(NlogN)的,看到logN,马上可以想到分治法。置于常数的空间,说明是在原来的链表上处理的。
我的做法是,先把原来的链表拆成长度相等的两段,分别对两段排序,然后merge一下,完全归并排序的思路。合并时,先确定新链表的头是哪个,然后用两个指针扫描两段,按照大小关系来连接后面的节点,当有一条为空时,把另一条接到最后就可以了。
ac代码如下,没有什么好说的了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ListNode* mergeList(ListNode *n1, ListNode *n2){ListNode *l1, *l2, *pre, *head;if(n1 == NULL)return n2;if(n2 == NULL)return n1;if(n1->val>n2->val){pre = head = n2;l1 = n2->next;l2 = n1;}else{pre = head = n1;l1 = n1->next;l2 = n2;}while(l1 != NULL && l2 != NULL){if(l1 -> val <= l2 ->val){pre->next = l1;pre = l1;l1 = l1->next;}else{pre->next = l2;pre = l2;l2 = l2->next;}}if(l1 != NULL){pre->next = l1;}else if(l2 != NULL){pre->next = l2;}return head;} class Solution {public: ListNode *sortList(ListNode *head) { if(head == NULL) return NULL; //cout<<"*"<<head->val<<endl; int length = 0; ListNode *mHead = head, *halfNode = head; while(mHead != NULL){length++;mHead = mHead->next;}if(length == 1)return head;int half = length/2;//cout<<length<<endl;for(int i=0;i<half&&halfNode;i++){mHead = halfNode;halfNode = halfNode->next;}mHead->next = NULL;ListNode *left = sortList(head);ListNode *right = sortList(halfNode);return mergeList(left, right); }};
0 0
- leetcode第一刷_Sort List
- leetcode第一刷_Sort Colors
- LeetCode之148_Sort List
- leetcode第一刷_Partition List
- leetcode第一刷_Rotate List
- leetcode第一刷_Insertion Sort List
- leetcode第一刷_Linked List Cycle
- leetcode第一刷_Linked List Cycle II
- leetcode第一刷_Reverse Linked List II
- leetcode第一刷_Copy List with Random Pointer
- leetcode第一刷_ Flatten Binary Tree to Linked List
- leetcode第一刷_Convert Sorted List to Binary Search Tree
- leetcode第一刷_Remove Duplicates from Sorted List II
- leetcode 第一刷_Remove Nth Node From End of List
- 算法_sort
- 排序_Sort
- c++_sort
- C++_sort
- (转载)Hibernate映射解析——七种映射关系
- 我先走的那一步
- 单向一对一唯一外键关联实例
- Android开发环境搭建
- 计算从1到N中1的出现次数
- leetcode第一刷_Sort List
- FreeSwitch安装音乐文件遇到的问题
- 单向一对一主键关联实例
- C++中基本类型
- c语言实现的静态链表 哥们第一篇 请各位大牛多指教
- TestFlight——完美的iOS App测试方案
- PMP-产品范围与项目范围区别
- C#中子线程操作主线程中窗体上控件的方法
- 语录