leetcode brush title 5

Today's topic is LeetCode brush 148 questions, medium difficulty

Subject is required constant level of spatial complexity sort list in case time complexity O (nlogn) of

Generally, data sorting, bubbling, insertion sort and selection are O (N2), and a quick sort and merge sort time complexity is O (nlogn). Therefore, the algorithm can be considered merge sort and quick sort

If the general sorting algorithm requires O (N) space complexity. Thus a need for improvement of the above algorithm

This article is the list of the selected merge sort algorithm. The algorithm also needs to be split and merge data. When segmentation strategy adopted is double pointer.

Then merge operation. Merge operation is to compare the value of the node list. Finally, return to the list after the merger. Specific code as follows:

public class SortList {
    public static void main(String[] args) {
        int[] a={-5,-10,-2,1,0,10,12,9,4};
        ListNode head=ListNode.generateListNode(a);
        head=SortList.sort(head);
        while (head!=null){
            System.out.println(head.val);
            head=head.next;
        }
    }
    public static ListNode sort(ListNode head){
        return head==null ? null: SortList.mergeSort (head); 
    } 
    public  static ListNode mergesort (ListNode head) {
         // boundary condition 
        IF (head.next == null ) return head;
         // define the double pointer, the linked list into two parts 
        ListNode FAST = head ; 
        ListNode SLOW = head; 
        ListNode pre = null ;
         the while (= FAST! null && fast.next =! null ) { 
            pre = SLOW; 
            FAST = fast.next.next; 
            SLOW =slow.next;
        }
        pre.next=null;
        ListNode left=head;
        ListNode right=slow;
        ListNode l=mergeSort(left);
        ListNode r=mergeSort(right);
        return merge(l,r);
    }
    public static ListNode merge(ListNode left,ListNode right){
        ListNode result=new ListNode(0);
        ListNode current=result;
        while (left!=null && right!=null){
            if (left.val<right.val){
                current.next=left;
                current=current.next;
                left=left.next;
            }else if (left.val>=right.val){
                current.next=right;
                right=right.next;
                current=current.next;
            }
            if (left!=null){
                current.next=left;
            }if (right!=null){
                current.next=right;
            }
        }
        return result.next;
    }
}

 

Guess you like

Origin www.cnblogs.com/cquer-xjtuer-lys/p/11329293.html