日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Sort List[leetcode] 由归并排序的递归和循环,到本题的两种解法

發布時間:2025/3/15 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Sort List[leetcode] 由归并排序的递归和循环,到本题的两种解法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

歸并排序能夠有兩種思路----top-down 和 bottom-up

top-down:

遞歸實現,將數組分成兩半。分別處理。再合并。

偽代碼例如以下

split ( A[], l, r) {if ( r - l < 2) return;m = (r + l) / 2;split ( A, l, m); //split A[l…m-1]split ( A, m, r); //split A[m…r-1]merge ( A, l, m, e); //merge A[l…m-1] and A[m…e-1] }
bottom-up:

循環實現。將數組看做n個長度為1的組數組。

用width控制每次merge的子數組長度。width每次翻倍

偽代碼例如以下

sort ( A[], n) {for (width = 1; width < n; width *= 2){for (i = 0; i < n; i += 2 * width){merge(A, i, min(i + width, n), min(i + 2 * width, n));}} }
Sort list中使用鏈表。不能在O(1)的時間內訪問隨意節點,同一時候注意要處理尾部節點的next,置為NULL

和上面的偽代碼類似,首先實現merge函數:

ListNode * merge(ListNode * h1, int s1, ListNode * h2, int s2){if (h2 == NULL) return h1;ListNode * h;if (h1->val < h2->val)h = advance(h1, s1);elseh = advance(h2, s2);ListNode * cur = h;while (s1 && s2){if (h1->val < h2->val)cur->next = advance(h1, s1);elsecur->next = advance(h2, s2);cur = cur->next;}if (s1){cur->next = h1;while(s1) advance(h1, s1);}if (s2){cur->next = h2;while(s2) advance(h2, s2);}return h;}ListNode * advance(ListNode * (& n), int & size){ListNode * temp = n;if (size == 1) n->next = NULL;n = n->next;size--;return temp;}


同一時候實現工具函數,訪問任何位置節點

ListNode * getNode(ListNode * head, int len){while (len -- && head) head = head->next;return head;}
循環版本號主函數例如以下:

ListNode *sortList(ListNode *head) {ListNode * cur = head;int size = 0;while (cur){size ++;cur = cur->next;}ListNode * pre;for (int w = 1; w <= size; w *= 2){cur = head;for (int i = 0; i < size; i+= w*2){ListNode * h1 = cur, * h2 = getNode(cur, w), * next = getNode(cur, 2 * w);cur = merge(h1, min(w, size - i), h2, min(w, size - i - w));if (i == 0) head = cur;else pre->next = cur;pre = getNode(cur, min(2 * w, size - i) - 1);cur = next;}}return head;}
遞歸版本號主函數例如以下:

ListNode *sortList(ListNode *head) {ListNode * cur = head;int size = 0;while (cur){size ++;cur = cur->next;}return sort(head, size - size / 2, getNode(head, size - size / 2), size / 2);}ListNode * sort(ListNode * h1, int s1, ListNode * h2, int s2){if (s1 == 0) return h2;if (s2 == 0) return h1;h1 = sort(h1, s1 - s1 / 2, getNode(h1, s1 - s1 / 2), s1 / 2);h2 = sort(h2, s2 - s2 / 2, getNode(h2, s2 - s2 / 2), s2 / 2);return merge(h1, s1, h2, s2);}


轉載于:https://www.cnblogs.com/blfbuaa/p/6743700.html

總結

以上是生活随笔為你收集整理的Sort List[leetcode] 由归并排序的递归和循环,到本题的两种解法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。