Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example
Given 1-3->2->null, sort it to 1->2->3->null.
SOLUTION:
这题是merge 2 sorted list的follow up,为什么这么说呢?因为在链表上做nlogn的排序,只有merge sort,同样的时间复杂度,也有heap sort,但是不太合适。
既然这样明确了merge sort,那么就开始,直接上递归就很方便!递归的时候需要中点,这个很麻烦,链表找中点是链表操作里比较费事儿的,但是用两个指针轻松解决,写一个findmid();,然后merge左右两边,也就是分治,left = sortlist(head),right = sortlist(mid)就ok了,分治的核心就是这一层看着一层,其他的事情交给其他层,这层就当他已经处理完了。
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: You should return the head of the sorted linked list, using constant space complexity. */ //思路就是:分治左右两边,然后递归,然后再把左右两边当作sorted listmerge一下 //用任何递归的想法都是,我写了这个公式的意思就是我已经排序好了。剩下的计算机自己干去 public ListNode sortList(ListNode head) { //值得注意的地方,第一次没写head.next ==null的情况 if (head == null || head.next ==null){ return head; } ListNode preMid = findMid(head); ListNode right = preMid.next; preMid.next = null; ListNode left = sortList(head); right = sortList(right); return merge(left, right); } private ListNode findMid(ListNode head){ if (head == null){ return head; } ListNode fast = head.next; ListNode slow = head; while (fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; } return slow; } private ListNode merge(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 = l1; head = head.next; l1 = l1.next; } else { head.next = l2; head = head.next; l2 = l2.next; } } if (l1 != null){ head.next = l1; } if (l2 != null){ head.next = l2; } return dummy.next; } }
时间: 2024-10-05 16:18:19