C# solution with 200ms runtime. No heap used


  • 0
    P

    class ListNode
    {
    public int val;
    public ListNode next;
    public ListNode(int x)
    {
    val = x;
    }
    }

    class Solution
    {
        public ListNode MergeKLists(ListNode[] lists)
        {
            Dictionary<int, int> dtk = new Dictionary<int, int>();
            ListNode start = null;
            ListNode t1 = null;
            bool boolfirs = false;
    
            foreach (ListNode lnd in lists) {
                ListNode temp = lnd;
                while (temp != null) {
                    if (dtk.ContainsKey(temp.val))
                        dtk[temp.val]++;
                    else
                        dtk.Add(temp.val, 1);
                    temp = temp.next;
                }
            }
            List<int> keylst = dtk.Keys.ToList(); // Dictionary' key holds the needed value and the value corresponding to key is the occurences of each key in linked lists.
            keylst.Sort();
            //create linked list from the dictionary.
            foreach (int key in keylst)
            {
                while (dtk[key] > 0)
                {
                    if (boolfirs == false)
                    {
                        t1 = new ListNode(key);
                        start = t1;
                        boolfirs = true;
                    }
                    else {
                        ListNode t2 = addToList(t1, key);
                        t1.next = t2;
                        t1 = t2;
                    }
                    dtk[key]--;
                }
            }
            return start;
        }
    
        private ListNode addToList(ListNode prev, int key)
        {
            ListNode t1 = new ListNode(key);
            t1.next = null;
            return t1;
        }
    }

Log in to reply
 

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