LeetCode 解题报告 Sort List

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

分析:对链表进行排序,如果是单链表用归并排序时最快的,并且在对数组进行归并的时候是需要用到O(n)的空间的,但是链表就不需要了,只要有O(1)的空间就够了,因为不需要辅助变量来存储。

首先是递归的将链表拆分开,然后将链表进行合并。

下面是代码:

<span style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;color:#333333;">public ListNode sortList(ListNode head){
		if(head == null || head.next == null)
			return head;
		//find the middle node
		ListNode fast = head,slow = head;
		while(fast.next != null && fast.next.next != null){
			fast = fast.next.next;
			slow = slow.next;
		}
		//diconnect the List
		fast = slow;
		slow = slow.next;
		fast.next = null;
		
		//Recursive 
		ListNode l1 = sortList(head);
		ListNode l2 = sortList(slow);
		//Meger the List
		return MegerList(l1,l2);
	}
	public ListNode MegerList(ListNode l1,ListNode l2){
		ListNode head = new ListNode(-1);
		for(ListNode p = head;l1 != null || l2 != null; p = p.next){
			int val1 = l1 == null?Integer.MAX_VALUE:l1.val;
			int val2 = l2 == null?Integer.MAX_VALUE:l2.val;
			if(val1 <= val2){
				p.next = l1;
				l1 = l1.next;
			}else{
				p.next = l2;
				l2 = l2.next;
			}
		} 
		return head.next;
	}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值