Middle-题目97:148. Sort List
来源:互联网 发布:java根据ip获取mac 编辑:程序博客网 时间:2024/06/05 08:02
题目原文:
Sort a linked list in O(n log n) time using constant space complexity.
题目大意:
对一个单链表排序,要求时间复杂度O(nlogn),空间复杂度O(1)
题目分析:
参考discuss中的算法,使用快排,取pivot为第一个节点值。
源码:(language:java)
public class Solution { public ListNode sortList(ListNode h){ if(h == null || h.next == null) return h; /*split into three list*/ ListNode fakesmall = new ListNode(0), small = fakesmall; ListNode fakelarge = new ListNode(0), large = fakelarge; ListNode fakeequal = new ListNode(0), equal = fakeequal; ListNode cur = h; // pivot is h. while(cur != null){ if(cur.val < h.val){ small.next = cur; small = small.next; } else if(cur.val == h.val){ equal.next = cur; equal = equal.next; } else{ large.next = cur; large = large.next; } cur = cur.next; } // put an end. small.next = equal.next = large.next = null; // merge them and return . merge reusing below one. merge for quicksort should be simplified. return merge(merge(sortList(fakesmall.next), sortList(fakelarge.next)),fakeequal.next) ; } private ListNode merge(ListNode h, ListNode m){ ListNode fake = new ListNode(0), cur = fake; while(h != null && m != null){ if(h.val < m.val){ cur.next = h; h = h.next; } else{ cur.next = m; m = m.next; } cur = cur.next; } cur.next = (h == null ? m : h); return fake.next; }}
成绩:
8ms,beats 42.09%,众数8ms,31.36%
cmershen的碎碎念:
数组的快排中pivot是使用三者取中法,而链表不是随机存取的,使用三者取中法要遍历一次链表,反而不能加速。
0 0
- Middle-题目97:148. Sort List
- Middle-题目63:147. Insertion Sort List
- Middle-题目28:75. Sort Colors
- Middle-题目113:324. Wiggle Sort II
- Middle-题目14:141. Linked List Cycle
- Middle-题目62:86. Partition List
- Middle-题目107:61. Rotate List
- Middle-题目109:143. Reorder List
- LeetCode题目4:Sort List
- LeetCode算法题目:Sort List
- Sort-----148. Sort List
- Middle-题目50:142. Linked List Cycle II
- Middle-题目53:114. Flatten Binary Tree to Linked List
- Middle-题目77:92. Reverse Linked List II
- Middle-题目84:82. Remove Duplicates from Sorted List II
- leetcode题目解答---Insertion Sort List
- LeetCode题目5:Insertion Sort List
- 148. Sort List leetcode list
- lucene 文档评分 及 CustomScoreQuery
- 贪心法——最优装载问题
- acm_Humble Numbers
- 刚毕业的时候遇到的一些问题,可能很简单但是也可以看一看
- 工资类(改)
- Middle-题目97:148. Sort List
- C++ limits头文件的用法(numeric_limits)
- HTML5标莶使用初级技巧
- java-对象管理-集合
- Middle-题目98:316. Remove Duplicate Letters
- hibernate如何使用hql语句查询时间区间段
- ScrollView和Listview结合使用
- 机器学习资源大全中文版
- FragmentTarnsaction.add 和 FragmentTarnsaction.replace区别