Extremely clean code - merge sort


  • 0
    R
    public class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if(lists.length == 0) {
                return null;
            }
            int l = 0, r = lists.length - 1;
            while(l < r) {
                while(l < r) lists[l] = merge(lists[l++], lists[r--]);
                l = 0;
            }
            return lists[0];
        }
        
        private ListNode merge(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(0);
            ListNode head = dummy;
            while(l1 != null && l2 != null) {
                if(l1.val < l2.val)  {
                    dummy.next = l1;
                    l1 = l1.next;
                } else {
                    dummy.next = l2;
                    l2 = l2.next;
                }
                dummy = dummy.next;
            }
            dummy.next = l1 == null ? l2 : l1;
            return head.next;
        }
    }

  • 0
    D

    Why double-nest a loop with the same condition?

    while(l<r) {
      while(l<r) {
        ...
    

Log in to reply
 

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