simple and clean Java code (divide and conquer)


  • 0
    M
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if (lists == null || lists.length == 0) {
                return null;
            }
            if (lists.length == 1) {
                return lists[0];
            }
            List<ListNode> list = new ArrayList<>();
            for (ListNode node : lists) {
                list.add(node);
            }
            ListNode head = new ListNode(0);
            head.next = divide(list);
            return head.next;
            
        }
        
        public ListNode divide(List<ListNode> list) {
            if (list.size() == 0) {
                return null;
            } else if (list.size() == 1) {
                return list.get(0);
            } else if (list.size() == 2) {
                return merge(list.get(0), list.get(1));
            } else {
                return merge(divide(list.subList(0, list.size() / 2)), divide(list.subList(list.size() / 2, list.size())));
            }
        }
        
        public ListNode merge(ListNode l1, ListNode l2) {
            if (l1 == null && l2 == null) {
                return null;
            }
            if (l1 == null) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
            ListNode head = new ListNode(0);
            ListNode current = head;
            while (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    current.next = l1;
                    l1 = l1.next;
                    current = current.next;
                } else {
                    current.next = l2;
                    l2 = l2.next;
                    current = current.next;
                }
            }
            if (l1 != null) {
                current.next = l1;
            }
            if (l2 != null) {
                current.next = l2;
            }
            return head.next;
        }
    }
    

Log in to reply
 

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