Two AC Solutions both in C#.


  • 0
    R

    public class Solution {
    public ListNode MergeKLists(ListNode[] lists)
    {
    // Solution1
    //var result = MergeKListsHelper(lists, 0, lists.Length - 1);
    //return result;

            // Solution2
            ListNode dummy = new ListNode(0);
            ListNode temp = dummy;
            int removeHeadIndex = -1;
            
            while(lists.Any(l => l != null))
            {
                ListNode min = new ListNode(Int32.MaxValue);
                for(int i =0;i<lists.Length;i++)
                {
                    if(lists[i] != null && lists[i].val<min.val)
                    {
                        min = lists[i];
                        removeHeadIndex = i;
                    }
                }
    
                temp.next = min;
                temp = temp.next;
                lists[removeHeadIndex] = lists[removeHeadIndex].next;
            }
    
            return dummy.next;
        }
        private ListNode MergeKListsHelper(ListNode[] lists, int start, int end)
        {
            if (start == end) return lists[start];
            if( start<end)
            {
                int mid = start + (end - start) / 2;// 不要用(start+end)/2 容易超过int的范围
                ListNode l1 = MergeKListsHelper(lists, start, mid);
                ListNode l2 = MergeKListsHelper(lists, mid + 1, end);
                var result = MergeTwo(l1, l2);
                return result;
            }
    
            return null;
        }
        private ListNode MergeTwo(ListNode l1, ListNode l2)
        {
            if (l1 == null)
                return l2;
            if (l2 == null)
                return l1;
            ListNode dummy = new ListNode(0);
            ListNode cur = dummy;
            while (l1 != null && l2 != null)
            {
                if (l1.val < l2.val)
                {
                    cur.next = l1;
                    l1 = l1.next;
                }
                else
                {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }
    
            if (l1 != null)
            {
                cur.next = l1;
            }
            if (l2 != null)
            {
                cur.next = l2;
            }
            return dummy.next;
        }
    

    }


Log in to reply
 

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