O(m + n) time complexity solution in Java


  • 0
    P

    Since we know both input lists are in non-decreasing order. Basically, we just compare on two lists and "pick" the smaller one to form the answer.

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null)
                return l2;
            if(l2 == null)
                return l1;
            ListNode fakeHead = new ListNode(-1);
            ListNode p = fakeHead;
            while(l1 != null && l2 != null){
                if(l1.val <= l2.val){
                    p.next = l1;
                    l1 = l1.next;
                }else{
                    p.next = l2;
                    l2 = l2.next;
                }
                p = p.next;
            }
            if(l1 == null)
                p.next = l2;
            if(l2 == null)
                p.next = l1;
            return fakeHead.next;
        }
    

Log in to reply
 

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