[LeetCode][JavaScript]Merge k Sorted Lists

來源:互聯網
上載者:User

標籤:

https://leetcode.com/submissions/detail/28015840/

Merge k Sorted Lists 

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 

 

直接使用了“Merge Two Sorted Lists”裡寫的方法。

http://www.cnblogs.com/Liok3187/p/4514347.html

兩兩比較就好了,每一輪比較都會減少一半lists的數量。

 

 1 /** 2  * Definition for singly-linked list. 3  * function ListNode(val) { 4  *     this.val = val; 5  *     this.next = null; 6  * } 7  */ 8 /** 9  * @param {ListNode[]} lists10  * @return {ListNode}11  */12 var mergeKLists = function(lists) {13     function mergeTwoLists(l1, l2) {14         if(l1 && l2 && l1.val !== undefined && l2.val !== undefined && l1.val > l2.val){15             var tmp = l1;16             l1 = l2;17             l2 = tmp;18         }19         var i = l1, j = l2, res = curr = [];20         if(i && i.val !== undefined){21             res = curr = i;22             i = i.next;23         }else if(j && j.val !== undefined){24             res = curr = j;25             j = j.next;26         }27         while(i && j && i.val !== undefined && j.val !== undefined){28             if(i.val < j.val){29                 curr.next = i;30                 i = i.next;31             }else{32                 curr.next = j;33                 j = j.next;34             }35             curr = curr.next;     36         }37         if(i && i.val !== undefined){38             curr.next = i;39         }else{40             curr.next = j;41         }42         return res;43     }44     45     var k;46     while(lists.length >= 2){47         var tmpList = [];48         for(k = lists.length - 1; k >= 0; k-=2){49             tmpList.push(mergeTwoLists(lists[k], lists[k - 1]));50         }51         if(k === 0){52             tmpList.push(lists[0]);53         }54         lists = tmpList;55     }56     57     return lists[0] || [];58 };

 

[LeetCode][JavaScript]Merge k Sorted Lists

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.