java solution use ArrayList


  • 0
    W
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            int n = lists.length;
            if(n==0)return null;
            List<ListNode> t = new ArrayList<ListNode>(); 
            while(n>1){
                for(int i=0;i+1<n;i=i+2){
                    t.add(mergeTwoLists(lists[i],lists[i+1]));
                }
                if(n%2!=0)t.add(lists[n-1]);
                n = t.size();
                lists = t.toArray(lists);
                t.clear();
            }
            return lists[0];
        }
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode res = new ListNode(0);
            ListNode curr = res;
            while(l1!=null&&l2!=null){
                if(l1.val<l2.val){
                    curr.next = l1;
                    l1=l1.next;
                }else{
                    curr.next = l2;
                    l2=l2.next;
                }
                curr = curr.next;
            }
            if(l1!=null)curr.next = l1;
            if(l2!=null)curr.next = l2;
            return res.next;
        }
    
    }
    

Log in to reply
 

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