Concise Java Solution -- Merge Sort O(n logn)


  • 0
    J
        public class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if (lists == null || lists.length == 0) {
                return null;
            }
            //5ms, 71.32%
            return mergeSort(lists, 0, lists.length);
        }
        private ListNode mergeSort(ListNode[] lists, int lo, int hi) {
            int n = hi - lo;
            if (n < 1) {
                return null;
            }
            if (n == 1) {
                return lists[lo];
            }
            int mid = lo + n/2;
            ListNode left = mergeSort(lists,lo, mid);
            ListNode right = mergeSort(lists, mid, hi);
            return merge(left, right);
        }
        private ListNode merge(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(0);
            ListNode tail = dummy;
            while (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    tail.next = l1;
                    l1 = l1.next;
                }else {
                    tail.next = l2;
                    l2 = l2.next;
                }
                tail = tail.next;
            }
            if (l1 != null) {
                tail.next = l1;
            }else {
                tail.next = l2;
            }
            return dummy.next;
        }
      }

Log in to reply
 

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