LeetCode - 148. Sort List

来源:互联网 发布:淘宝卖家怎么退货退款 编辑:程序博客网 时间:2024/04/30 11:24

这道题分为三步,首先通过fast slow双指针的方法找到list中间的元素,其次将list分为两半分别对它们进行排序,最后将它们merge起来。注意这道题目同样使用了递归的思想,是merge sort的linked list版本。时间复杂度O(nlogn),代码如下:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution{    ListNode merge(ListNode l1, ListNode l2){        ListNode dummyNode = new ListNode(0);        ListNode p = dummyNode;        while(l1 != null && l2 != null){            if(l1.val < l2.val){                p.next = l1;                l1 = l1.next;            }else{                p.next = l2;                l2 = l2.next;            }            p = p.next;        }        if(l1 != null) p.next = l1;        if(l2 != null) p.next = l2;        return dummyNode.next;    }        public ListNode sortList(ListNode head){        if(head == null || head.next == null){            return head;        }        // Cut the list to two halves        ListNode prev = null;        ListNode slow = head;        ListNode fast = head;        while(fast != null && fast.next != null){            prev = slow;            slow = slow.next;            fast = fast.next.next;        }        prev.next = null;        // Sort two halves        ListNode l1 = sortList(head);        ListNode l2 = sortList(slow);        // Merge two halves        return merge(l1, l2);    }}


知识点:

1. 在Linked List中通过使用fast runner, slow runner找到Linked List的中点

2. 如何将两个sorted的list merge起来

3. merge sort在Linked List上面的写法

4. 递归思想在Linked List上面的体现

5. 总的来说这个题目的代码易懂优雅,而且包含了很多小的知识点,最好背下来

0 0
原创粉丝点击