這是我的第一個自己ak的分治題目?。?!好耶?。。湴聊?mark hidden color="red">文章來源:http://www.zghlxwxcb.cn/news/detail-792481.html
思路參考:148. 排序鏈表(歸并排序)文章來源地址http://www.zghlxwxcb.cn/news/detail-792481.html
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
return dfs(lists, 0, lists.length - 1);
}
public ListNode dfs(ListNode[] lists, int head, int tail) {
if (head > tail) return null;
if (head == tail) return lists[head];
int mid = (head + tail) / 2;
ListNode node1 = dfs(lists, head, mid);
ListNode node2 = dfs(lists, mid + 1, tail);
ListNode node = merge(node1, node2);
return node;
}
public ListNode merge(ListNode node1, ListNode node2) {
ListNode node = new ListNode(0);
ListNode temp = node, temp1 = node1, temp2 = node2;
while (temp1 != null && temp2 != null) {
if (temp1.val < temp2.val) {
temp.next = temp1;
temp1 = temp1.next;
} else {
temp.next = temp2;
temp2 = temp2.next;
}
temp = temp.next;
}
if (temp1 != null) temp.next = temp1;
if (temp2 != null) temp.next = temp2;
return node.next;
}
}
到了這里,關(guān)于23. 合并 K 個升序鏈表(遞歸分治)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!