Sort list, Time overhead O (NLOGN), Space overhead O (1)

Source: Internet
Author: User

Leetcode on the topic:

Sort A linked list inO(NLogN) time using constant space complexity.

The initial idea was to hurry up because of the requirement for space overhead O (1), but some cases could not be passed, and everyone understood that the worst time spent in the queue O (n^2)

So you still have to use the merge sort, the O (n) space overhead is generally required for the array merge sort, but there is also the in-place merge sort to do the O (1) space overhead, which is too complex

Always remember.

But for the linked list, it is relatively simple to do O (1) space overhead, just pay attention to some boundary conditions.

Public ListNode sortlist (ListNode head) {if (head==null| | Head.next==null) return head;        ListNode Tail=head;int len=1;            while (tail.next!=null) {tail=tail.next;        len++;        } head=mergesort (Null,head,len); return head;} Return the head of sorted list.private ListNode mergesort (listnode prehead,listnode head, int len) {if (head==null| | len<=1) return Head;int left=len/2;int Right=len-left;//sort left Parthead=mergesort (prehead,head,left);//sort Right Partlistnode pmid=head;for (int i=0;i<left-1;i++) {pmid=pmid.next;} MergeSort (pmid,pmid.next,right);//p1 points to left part head,p2 points to right part headlistnode P1=head,p2=pmid.next; ListNode pre1=prehead,pre2=pmid;//new Head is little one between left head and right head. if (p1.val>p2.val) head=p2;while (left>0&&right>0) {//if p2.val<p1.val move P2 previous to P1.if ( P1.val>p2.val) {//delete p2pre2.next=p2.next;//add p2 previous to p1p2.next=p1;if (pre1!=null) {pre1.next=p2;} Pre1 move to P2PRE1=P2;//P2 move to pre2.nextp2=pre2.next;right--;} else{pre1=p1;p1=p1.next;left--;}} return head;}



Sort list, Time overhead O (NLOGN), Space overhead O (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.