티스토리 뷰

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

 

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

문제 : lists로 주어진 링크드리스트를 하나의 링크드리스트로 합쳐서 리턴해라

 

 

풀이

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        
        //배열에 val 값을 담는다.
        ArrayList<Integer> arr = new ArrayList<>();        
        for(ListNode node : lists){
            while(node != null){
                arr.add(node.val);
                node = node.next;
            }
        }
        //배열을 정렬을한다.
        Collections.sort(arr);
        
        //각 링크드 리스트로 연결을 시켜준다.
        ListNode node = new ListNode(arr.get(0));
        ListNode tmp = node;
        for(int i=1;i<arr.size();i++){
            ListNode nodeNext = new ListNode(arr.get(i));
            tmp.next = nodeNext;
            tmp = tmp.next;
        }
        
        
        return node;    
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함