Friday, April 10, 2015

148. Sort List Leetcode Java

Sort a linked list in O(n log n) time using constant space complexity.
Solution:
Strictly speaking, my solution is not a constant space solution.
I use the idea of merge sort. So the basic steps are:
Divide the current list to half till only one node or no node in the list, then merge them back by using merge two sorted list.
The extra space should be the recursion tree space which is O(logn) and the time complexity will be O(nlogn)
 public ListNode sortList(ListNode head) {  
     return mergeSort(head);  
   }  
   public ListNode mergeSort(ListNode head){  
     if(head==null || head.next==null) return head;  
     ListNode runner=head.next;  
     ListNode walker=head;  
     while(runner!=null && runner.next!=null){  
       walker=walker.next;  
       runner=runner.next.next;  
     }  
     ListNode head2=walker.next;  
     walker.next=null;  
     return MergeTwo(mergeSort(head),mergeSort(head2));  
   }  
   public ListNode MergeTwo(ListNode l1,ListNode l2){  
     ListNode preDummy=new ListNode(0);  
     preDummy.next=l1;  
     ListNode pre=preDummy;  
     while(pre.next!=null && l2!=null){  
       if(pre.next.val>l2.val){  
         ListNode temp=l2.next;  
         l2.next=pre.next;  
         pre.next=l2;  
         l2=temp;  
       }  
       pre=pre.next;  
     }  
     if(pre.next==null) pre.next=l2;  
     return preDummy.next;  
   }  

No comments:

Post a Comment