Skip to content

Latest commit

Β 

History

History
87 lines (64 loc) Β· 2.31 KB

dev-jonghoonpark.md

File metadata and controls

87 lines (64 loc) Β· 2.31 KB

풀이 1

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;
    }
}

TC, SC

λ¬Έμ œμ—μ„œ λ‹€μŒκ³Ό 같이 μ •μ˜κ°€ λ˜μ–΄μžˆλ‹€.

k == lists.length

μΆ”κ°€μ μœΌλ‘œ n을 list λ“€μ˜ item 수의 총합 이라고 μ •μ˜ν•˜μ˜€μ„ λ•Œ

μ‹œκ°„λ³΅μž‘λ„λŠ” O(n * k), κ³΅κ°„λ³΅μž‘λ„λŠ” O(n) 이닀.

풀이 2: stream μ‚¬μš©ν•΄μ„œ ν’€κΈ°

μš°μ„  λ‹€ ν•˜λ‚˜μ˜ λ¦¬μŠ€νŠΈμ— ν•©μΉœ ν›„ μ •λ ¬ν•œλ‹€.

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;
    }
}

μ˜ˆμƒκ³ΌλŠ” λ‹€λ₯΄κ²Œ 였히렀 이 방식이 더 적은 μ‹€ν–‰μ‹œκ°„μœΌλ‘œ μ™„λ£Œλ˜μ—ˆλ‹€.

TC, SC

n을 list λ“€μ˜ item 수의 총합 이라고 μ •μ˜ν•˜μ˜€μ„ λ•Œ, μ‹œκ°„λ³΅μž‘λ„λŠ” O(nlogn), κ³΅κ°„λ³΅μž‘λ„λŠ” O(n) 이닀.