Time exceeded by twisting a little bit from "Merge Two Sorted Array"


  • 0
    L

    Got time exceeded. Basically, it's just a little twist from "Merge Two Sorted Array". Any ideas that can pass the test cases?

    public class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if (lists == null || lists.length == 0) return null;
            if (lists.length == 1) return lists[0];
            
            ListNode result = mergeTwoLists(lists[0], lists[1]);
            int i = 2;
            while (i < lists.length) {
                result = mergeTwoLists(result, lists[i]);
                i += 1;
            }
            return result;
        }
        
        private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(0);
    		ListNode p = head;
    		
    		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 = l1; 
    		}
    			
    		if (l2 != null) {
    			p.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.