Wanted to Implement the same solution as mergeTwoLists


  • 0
    K

    I have 129/130 test cases passing. The last test case is huge and I get time exceeded on that one. Is there a way to optimize this?

    public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        
        ListNode l4 = new ListNode(0);
    
        for (int i = 0; i < lists.length; i++) 
        {
            l4.next = mergeTwoLists(l4.next, lists[i]);
        }
        
        return l4.next;
    }
    
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        
        ListNode l3 = new ListNode(0);
        ListNode c3 = l3;
        
        while (l1 != null || l2 != null)
        {
            if (l1 == null)
            {
                c3.next = l2;
                return l3.next;
            }
            
            if (l2 == null)
            {
                c3.next = l1;
                return l3.next;
            }
            
            if (l1.val > l2.val)
            {
                c3.next = l2;
                l2 = l2.next;
                c3 = c3.next;
            }
            else
            {
                c3.next = l1;
                l1 = l1.next;
                c3 = c3.next;
            }
            
        }
        
        return l3.next;
    }
    

    }


Log in to reply
 

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