JAVA Concise solution


  • 0
    F
    public class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            
            if (lists == null || lists.length == 0)
                return null;
            return mergeLists(lists, 0, lists.length-1);
        }
        
        private ListNode mergeLists(ListNode[] lists, int beg, int end) {
            
            if (beg == end) {
                return lists[beg];
            }
            
            int mid = beg + (end-beg)/2;
            ListNode left = mergeLists(lists, beg, mid);
            ListNode right = mergeLists(lists, mid+1, end);
            
            return mergeTwoLists(left, right);
        }
        
        private ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode dummy = new ListNode(0);
            ListNode cur = dummy;
            
            if (list1 == null) {
                return list2;
            }
            if (list2 == null) {
                return list1;
            }
            
            while (list1 != null && list2 != null) {
                if (list1.val < list2.val) {
                    cur.next = list1;
                    list1 = list1.next;
                }
                else {
                    cur.next = list2;
                    list2 = list2.next;
                }
                cur = cur.next;
            }
            
            cur.next = list1 != null ? list1 : list2;
            return dummy.next;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.