148 Sort List

| 分类 leetcode  | 标签 sort 

Sort a linked list in O(n log n) time using constant space complexity.
/*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
/
public class Solution {
public ListNode sortList(ListNode head) {
}
}

1

一看到O(nlogn)就会想到排序算法,刚好归并排序适用于数组和链表,时间复杂度是O(nlogn)。 注意findMid()这个方法,这个是O(n)时间的查找链表中间元素的方法,使用两个指针遍历链表,
使两个指针之间有某种关系来解决问题,寻找链表中倒数第k个元素也是这种方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public ListNode mergeSort(ListNode head){
        if(head == null || head.next == null) return head;
        ListNode mid = findMid(head);
        ListNode r = mid.next;
        mid.next = null;
        ListNode left = mergeSort(head);
        ListNode right = mergeSort(r);
        return merge(left,right);
    }
    private  ListNode merge(ListNode left,ListNode right){
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        while(left != null && right != null){
            if(left.val < right.val){
                cur.next = left;
                left = left.next;
            }else{
                cur.next = right;
                right  = right.next;
            }
            cur = cur.next;
        }
        cur.next = (left == null) ? right : left;
        return dummyHead.next;
    }
    private ListNode findMid(ListNode head){
        ListNode slow,fast;
        slow = fast = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

2 leetcode discuss

most votes的方法也是这个。


上一篇     下一篇