23. Merge k Sorted Lists - LeetCode
阿新 • • 發佈:2018-08-02
.com pre pro java實現 des desc -s pub mini
Question
23.?Merge k Sorted Lists
Solution
題目大意:合並鏈表數組(每個鏈表中的元素是有序的),要求合並後的鏈表也是有序的
思路:遍歷鏈表數組,每次取最小節點
Java實現:
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; }
23. Merge k Sorted Lists - LeetCode