題目大意:合併鏈表數組(每一個鏈表中的元素是有序的),要求合併後的鏈表也是有序的數組
思路:遍歷鏈表數組,每次取最小節點code
Java實現:ip
public ListNode mergeKLists(ListNode[] lists) { ListNode preHead = new ListNode(0); ListNode minNode = getMinNode(lists); ListNode tmpNode = preHead; while (minNode != null) { tmpNode.next = minNode; tmpNode = minNode; minNode = getMinNode(lists); } return preHead.next; } ListNode getMinNode(ListNode[] lists) { int minIdx = -1; int minVal = 0; for (int i=0; i<lists.length; i++) { ListNode cur = lists[i]; if (cur != null) { if (minIdx == -1 || cur.val < minVal) { minIdx = i; minVal = cur.val; } } } if (minIdx != -1) { ListNode tmpNode = lists[minIdx]; lists[minIdx] = tmpNode.next; return tmpNode; } return null; }