首页 > 代码库 > Sort List leetcode java
Sort List leetcode java
题目:
Sort a linked list in O(n log n) time using constant space complexity.
题解:
考虑到要求用O(nlogn)的时间复杂度和constant space complexity来sort list,自然而然想到了merge sort方法。同时我们还已经做过了merge k sorted list和merge 2 sorted list。这样这个问题就比较容易了。
不过这道题要找linkedlist中点,那当然就要用最经典的faster和slower方法,faster速度是slower的两倍,当faster到链尾时,slower就是中点,slower的next是下一半的开始点。
解决了这些问题,题目就很容易解出了。
代码如下:
1 public ListNode sortList(ListNode head) {
2 if(head == null|| head.next == null)
3 return head;
4 ListNode slow = head, fast = head, firsthalf = head;
5 while(fast.next!=null&&fast.next.next!=null){
6 slow = slow.next;
7 fast = fast.next.next;
8 }
9 ListNode secondhalf = slow.next;
10 slow.next = null;
11
12 ListNode leftlist = null, rightlist =null;
13 if(firsthalf!=secondhalf){
14 leftlist = sortList(firsthalf);
15 rightlist = sortList(secondhalf);
16 }
17 return mergeTwoLists(leftlist, rightlist);
18 }
19
20 public ListNode mergeTwoLists(ListNode leftlist, ListNode rightlist){
21 if(rightlist == null)
22 return leftlist;
23 if(leftlist == null)
24 return rightlist;
25
26 ListNode fakehead = new ListNode(-1);
27 ListNode ptr = fakehead;
28 while(rightlist!=null&&leftlist!=null){
29 if(rightlist.val<leftlist.val){
30 ptr.next = rightlist;
31 ptr = ptr.next;
32 rightlist = rightlist.next;
33 }else{
34 ptr.next = leftlist;
35 ptr = ptr.next;
36 leftlist = leftlist.next;
37 }
38 }
39
40 if(rightlist!=null)
41 ptr.next = rightlist;
42 if(leftlist!=null)
43 ptr.next = leftlist;
44
45 return fakehead.next;
46 }
2 if(head == null|| head.next == null)
3 return head;
4 ListNode slow = head, fast = head, firsthalf = head;
5 while(fast.next!=null&&fast.next.next!=null){
6 slow = slow.next;
7 fast = fast.next.next;
8 }
9 ListNode secondhalf = slow.next;
10 slow.next = null;
11
12 ListNode leftlist = null, rightlist =null;
13 if(firsthalf!=secondhalf){
14 leftlist = sortList(firsthalf);
15 rightlist = sortList(secondhalf);
16 }
17 return mergeTwoLists(leftlist, rightlist);
18 }
19
20 public ListNode mergeTwoLists(ListNode leftlist, ListNode rightlist){
21 if(rightlist == null)
22 return leftlist;
23 if(leftlist == null)
24 return rightlist;
25
26 ListNode fakehead = new ListNode(-1);
27 ListNode ptr = fakehead;
28 while(rightlist!=null&&leftlist!=null){
29 if(rightlist.val<leftlist.val){
30 ptr.next = rightlist;
31 ptr = ptr.next;
32 rightlist = rightlist.next;
33 }else{
34 ptr.next = leftlist;
35 ptr = ptr.next;
36 leftlist = leftlist.next;
37 }
38 }
39
40 if(rightlist!=null)
41 ptr.next = rightlist;
42 if(leftlist!=null)
43 ptr.next = leftlist;
44
45 return fakehead.next;
46 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。