Leetcode

23. Merge k Sorted Lists

by hooni posted Apr 14, 2020
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        /*
        ListNode result = lists[0];
        ListNode last = result;
        
        for(int i=1; i<lists.length; i++){
            while(last.next != null){
                last = last.next;
            }
            ListNode tmp = lists[i];
            last.next = tmp;
        }
        return result;
        */
        if(lists.length == 0){
            return null;
        }
        
        ListNode left = null;
        int index = 0;
        while(index<lists.length && left==null){
            if(lists[index] != null){
                left = lists[index];
            }
            index++;
        }
        
        while(index<lists.length){
            if(lists[index] != null){
                ListNode right = lists[index];
                left = merge(left, right);
            }
            index++;
        }
        
        return left;
    }
    
    public ListNode merge(ListNode left, ListNode right){
        if(left == null){
            return right;
        }
        
        if(right == null){
            return left;
        }
        
        ListNode result = null;
        if(left.val < right.val){
            result = left;
            result.next = merge(left.next, right);
        }else{
            result = right;
            result.next = merge(left, right.next);
        }
        
        return result;
    }
}

[문제] https://leetcode.com/problems/merge-k-sorted-lists/