- λ¬Έμ : https://leetcode.com/problems/merge-k-sorted-lists/
- νμ΄: https://algorithm.jonghoonpark.com/2024/02/19/leetcode-23
listsλ₯Ό μννλ©΄μ κ°μ₯ μμ μλ₯Ό κ°μ§ λ Έλλ₯Ό μ°Ύκ³ , κ·Έ λ Έλλ₯Ό mergedList μ μΆκ°νλ€.
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode mergedList = new ListNode();
ListNode current = mergedList;
while (true) {
int minIndex = -1;
int currentMin = Integer.MAX_VALUE;
for (int i = 0; i < lists.length; i++) {
ListNode node = lists[i];
if (node != null && node.val < currentMin) {
minIndex = i;
currentMin = node.val;
}
}
if (minIndex == -1) {
break;
}
current.next = lists[minIndex];
lists[minIndex] = lists[minIndex].next;
current = current.next;
}
return mergedList.next;
}
}
λ¬Έμ μμ λ€μκ³Ό κ°μ΄ μ μκ° λμ΄μλ€.
k == lists.length
μΆκ°μ μΌλ‘ nμ list λ€μ item μμ μ΄ν© μ΄λΌκ³ μ μνμμ λ
μκ°λ³΅μ‘λλ O(n * k)
, 곡κ°λ³΅μ‘λλ O(n)
μ΄λ€.
μ°μ λ€ νλμ 리μ€νΈμ ν©μΉ ν μ λ ¬νλ€.
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
List<ListNode> mergedListNode = new ArrayList<>();
for (ListNode listNode : lists) {
ListNode current = listNode;
while (current != null) {
mergedListNode.add(current);
current = current.next;
}
}
ListNode listNode = new ListNode();
final ListNode[] current = {listNode};
mergedListNode.stream().sorted(Comparator.comparingInt(node -> node.val))
.forEach(node -> {
current[0].next = node;
current[0] = current[0].next;
});
return listNode.next;
}
}
μμκ³Όλ λ€λ₯΄κ² μ€νλ € μ΄ λ°©μμ΄ λ μ μ μ€νμκ°μΌλ‘ μλ£λμλ€.
nμ list λ€μ item μμ μ΄ν© μ΄λΌκ³ μ μνμμ λ, μκ°λ³΅μ‘λλ O(nlogn)
, 곡κ°λ³΅μ‘λλ O(n)
μ΄λ€.