Step-by-Step
[Java] Daily LeetCode Challenge 23. Merge k Sorted Lists 본문
https://leetcode.com/problems/merge-k-sorted-lists/
Merge k Sorted Lists - LeetCode
Can you solve this real interview question? Merge k Sorted Lists - 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: lis
leetcode.com
LinkedList 값 받아오면서 null값만 적절히 체크해주면 금방 풀리는 문제
LeetCode에는 리스트 관련 문제들이 많은 듯 하다
[코드]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0)
return null;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i=0; i<lists.length; i++){
ListNode node = lists[i];
while(node != null){
pq.add(node.val);
node = node.next;
}
}
if(pq.size() == 0)
return null;
ListNode node = new ListNode(pq.poll());
while(!pq.isEmpty()){
ListNode now = new ListNode(pq.poll(), node);
node = now;
}
return node;
}
}
'언어 > JAVA' 카테고리의 다른 글
Comments