首页 > 其他 > 详细

LeetCode 148 Sort List

时间:2014-10-22 12:53:49      阅读:226      评论:0      收藏:0      [点我收藏+]

Sort a linked list in O(n log n) time using constant space complexity.

思路:要想时间复杂度达到O(n log n) ,那么有两种,一种是合并排序,另一种是快速排序,而要想空间复杂度为常数,那么只能使用递归,本人使用的是递归的合并排序,代码如下:
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
   private ListNode merge(ListNode l1, ListNode l2) {
        if(l1==null&&l2==null) return null;
        ListNode head=new ListNode (-1);
        ListNode pNode=head;
        while(l1!=null||l2!=null){
			if(l1==null) {
				pNode.next=l2;
				return head.next;
			}
			if(l2==null){
				pNode.next=l1;
				return head.next;
			}
            if(l1.val>l2.val){
				pNode.next=l2;
				l2=l2.next;
            }else {
				pNode.next=l1;
				l1=l1.next;
            }
            pNode=pNode.next;                   
        }
        return head.next;
    }
   private ListNode mergeSort(ListNode head){
       if(head==null||head.next==null)   //just one element
           return head;
       ListNode p=head, q=head, pre=null;
       while(q!=null&&q.next!=null){
           q=q.next.next;
           pre=p;
           p=p.next;  //divide into two parts
       }
       pre.next=null;
       ListNode lhalf=mergeSort(head);
       ListNode rhalf=mergeSort(p);  //recursive
       return merge(lhalf, rhalf);   //merge
   }
    public ListNode sortList(ListNode head) {
        return mergeSort( head);
    }
}



LeetCode 148 Sort List

原文:http://blog.csdn.net/mlweixiao/article/details/40373915

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!