方法1 :暴力法
用一個數組將所有的鏈表節點放入數組中然後進行直接排序
/**
* 暴力法
* @param lists
* @return
*/
public ListNode mergeKLists1(ListNode[] lists){
int n = 0;
ListNode ans = new ListNode(0);
ArrayList<Integer> arrayList = new ArrayList<>();
for (ListNode list : lists) {
while (list.next != null){
arrayList.add(list.val);
list = list.next;
}
}
arrayList.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
ListNode temp = ans;
for (Integer integer : arrayList) {
ans.val = integer;
ans = ans.next;
}
return ans;
}
方法2:歸併思想
每次合併兩個鏈表直到只有一個鏈表爲止。
圖片來自力扣中國leetcode題解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Main {
public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if(len == 0) return null;
return merge(lists,0,lists.length-1);
}
public static ListNode merge(ListNode[] lists,int l,int r){
if(r == l){
return lists[l];
}
int mid = (r - l) / 2 + l;
ListNode l1 = merge(lists,l,mid);
ListNode l2 = merge(lists,mid+1,r);
return merge(l1,l2);
}
//合併兩個鏈表
public static ListNode merge(ListNode l1, ListNode l2) {
ListNode ansHead = new ListNode(0);
ListNode node = ansHead;
while(l1!=null && l2!=null){
if(l1.val>=l2.val){
node.next = l2;
l2 = l2.next;
}else{
node.next = l1;
l1 = l1.next;
}
node = node.next;
}
if(l1==null){
node.next = l2;
}
if(l2==null){
node.next = l1;
}
return ansHead.next;
}
}