티스토리 뷰
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;
}
}
'알고리즘' 카테고리의 다른 글
leetcode - 389. Find the Difference (0) | 2022.02.07 |
---|---|
leetcode - 80. Remove Duplicates from Sorted Array II (0) | 2022.02.06 |
leetcode - 121. Best Time to Buy and Sell Stock (0) | 2022.02.01 |
leetcode - 134. Gas Station (0) | 2022.01.25 |
leetcode - 941. Valid Mountain Array (0) | 2022.01.25 |