leetcode:Sort List(一个链表的归并排序)
Sort a linked list in?O(n?log?n) time using constant space complexity.
分析:題目要求時間復雜度為O(nlogn),所以不能用quickSort(最壞O(n^2)),可以使用mergeSort.
對一個鏈表進行歸并排序,首先注意歸并排序的基本思想:找到鏈表的middle節點,然后遞歸對前半部分和后半部分分別進行歸并排序,最后對兩個以排好序的鏈表進行Merge。
而找到鏈表中間點可以利用快慢指針的思想:用兩個指針,一個每次走兩步,一個走一步,知道快的走到了末尾,然后慢的所在位置就是中間位置,這樣就分成了兩個鏈表。
merge時,把兩段頭部節點值比較,用一個 p 指向較小的,且記錄第一個節點,然后 兩段的頭一步一步向后走,p也一直向后走,總是指向較小節點,直至其中一個頭為NULL,處理剩下的元素,最后返回記錄的頭節點即可。
code如下:
class Solution { public: ListNode *sortList(ListNode *head) { if(!head||!head->next) return head; return mergeSort(head); } ListNode * mergeSort(ListNode *head){ if(!head||!head->next) //just one element return head; ListNode *p=head, *q=head, *pre=NULL; while(q&&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 } ListNode * merge(ListNode *lh, ListNode *rh){ ListNode *temp=new ListNode(0); ListNode *p=temp; while(lh&&rh){ if(lh->val<=rh->val){ p->next=lh; lh=lh->next; } else{ p->next=rh; rh=rh->next; } p=p->next; } if(!lh) p->next=rh; else p->next=lh; p=temp->next; temp->next=NULL; delete temp; return p; } };?
?
?
python:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = Noneclass Solution(object):def sortList(self, head):if not head or not head.next:return head slow = headfast = head.next while fast and fast.next:slow = slow.nextfast = fast.next.nextrlist = self.sortList(slow.next)slow.next = Nonellist = self.sortList(head) return self.mergeList(llist, rlist)def mergeList(self, l1, l2): nHead = ListNode(0)lastnode = nHead while l1 and l2: if l1.val < l2.val:lastnode.next = l1l1 = l1.nextelse:lastnode.next = l2l2 = l2.nextlastnode = lastnode.next lastnode.next = l1 or l2 return nHead.nextPython語言是一款對縮進非常敏感的語言,在編譯時會出現這樣的錯IndentationError:expected an indented block說明此處需要縮進,你只要在出現錯誤的那一行,按空格或Tab(但不能混用)鍵縮進就行。 ----(有冒號的下一行往往要縮進,該縮進就縮進)
ps:標記部分若set fast = head, the code will be beyond the time. The difference of the two situations are as follows:?
?
轉載于:https://www.cnblogs.com/carsonzhu/p/4857684.html
總結
以上是生活随笔為你收集整理的leetcode:Sort List(一个链表的归并排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell中trap捕捉到信号的处理
- 下一篇: SQL查询下级节点