leetcode sort List

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   ar   for   art   

Sort a linked list in O(n log n) time using constant space complexity./** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *sortList(ListNode *head) {   if(!head)          return NULL;      int k=0;      ListNode *p=head;      while(p)      {          k++;          p=p->next;      }      if(k==1)          return head;      int l=k/2;    //計算結點個數,將鏈表分開。      p=head;      ListNode *q=head,*t=NULL;      for(int i=0;i<l && q ;i++)      {          if(i==l-1)              t=q;          q=q->next;      }      if(t)          t->next=NULL;//將鏈表分開。      p=sortList(p);//分別對兩段排序      q=sortList(q);      ListNode *hd=NULL,*pp=NULL;      while(p&&q)//合并      {          if(p->val<=q->val)          {              if(!hd)                             pp=hd=p;                         else             {                  pp->next=p;                  pp=p;              }              p=p->next;          }          else         {              if(!hd)                             hd=pp=q;                         else             {                  pp->next=q;                  pp=q;              }              q=q->next;          }      }      if(p)          pp->next=p;      if(q)          pp->next=q;      return hd;  }  };

分析如下:
挺有意思的一道題目。表面上看,能夠有O(n lgn)時間複雜度的演算法為,快速排序,堆排序,歸併排序,三者的空間複雜度分別為O(1), O(N),O(N)
所以一開始,我想著用快速排序的方法來解決,但是發現代碼很難寫出來。於是網上看了一下提示,發現其實方法選錯了。應該使用的方法是歸併排序。

通常而言,也就是針對數組而言,歸併排序的空間複雜度為O(N), 你需要開出O(N)的額外空間來容納數組,來表示歸併後的順序。但是,對於鏈表而言,你可以省下這部分空間的開銷,你只需要改變節點的next指標的指向,就可以表示新的歸併後的順序了,所以空間複雜度陡然降到了O(1)

 

小結:

(1)挺有意思的一道題目,需要在新的條件和環境下去思考舊的結論是否依然成立。

(2)快速排序和歸併排序的時間複雜度都是O(N lgN),但是CLRS說了,實踐證明快速排序的速度比歸併排序的速度更快,為什麼呢?另外其實這個結論是有限制範圍的,當對數組進行排序的時候,這個結論適用。為什麼對於鏈表,卻是歸併排序的速度優於快速排序呢?這裡看到的一段對比說得挺好,直接抄過來。

One of the main sources of efficiency in quicksort is locality of reference, where the computer hardware is optimized so that accessing memory locations that are near one another tends to be faster than accessing memory locations scattered throughout memory. The partitioning step in quicksort typically has excellent locality, since it accesses consecutive array elements near the front and the back. As a result, quicksort tends to perform much better than other sorting algorithms like heapsort even though it often does roughly the same number of comparisons and swaps, since in the case of heapsort the accesses are more scattered.

Additionally, quicksort is typically much faster than other sorting algorithms because it operates in-place, without needing to create any auxiliary arrays to hold temporary values. Compared to something like merge sort, this can be a huge advantage because the time required to allocate and deallocate the auxiliary arrays can be noticeable. Operating in-place also improves quicksort‘s locality.

When working with linked lists, neither of these advantages necessarily applies. Because linked list cells are often scattered throughout memory, there is no locality bonus to accessing adjacent linked list cells. Consequently, one of quicksort‘s huge performance advantages is eaten up. Similarly, the benefits of working in-place no longer apply, since merge sort‘s linked list algorithm doesn‘t need any extra auxiliary storage space.

That said, quicksort is still very fast on linked lists. Merge sort just tends to be faster because it more evenly splits the lists in half and does less work per iteration to do a merge than to do the partitioning step.

 

歸納一下,就是說,如果待排序的元素儲存在數組中,那麼快速排序相對歸併排序就有兩個原因更快。一是,可以很快地進行元素的讀取(相對於鏈表,數組的元素是順序擺放的,而鏈表的元素是隨機擺放的),數組的partion這步就比鏈表的partion這步快。二是,歸併排序在merge階段需要輔助數組,需要申請O(N)的空間,申請空間也是需要時間的。而快排不需要額外申請空間。如果待排序的元素儲存在鏈表中,快排的優點就變成了缺點。歸併排序於是就速度更優了。

leetcode sort List

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.