My C# solution with SortedSet


  • 1
    S

    public class Solution {
    public ListNode MergeKLists(ListNode[] lists)
    {
    if(lists==null || lists.Count()==0)
    return null;
    var ss = new SortedSet<Tuple<ListNode,int>>(Comparer<Tuple<ListNode,int>>.Create((a,b) => a.Item1.val == b.Item1.val?a.Item2-b.Item2 : a.Item1.val - b.Item1.val));
    var count = 0;
    foreach(var node in lists)
    {
    if(node!=null)
    {
    ss.Add(new Tuple<ListNode,int>(node, count++));
    }
    }

        var dummy = new ListNode(0);
        var pre = dummy;
        while(ss.Count>0)
        {
            var t = ss.Min.Item1;
            ss.Remove(ss.Min);
            pre.next = t;
            if(t.next != null)
            {
                ss.Add(new Tuple<ListNode, int>(t.next,count++));
            }
            pre = pre.next;
        }
        
        return dummy.next;
    }
    

    }


Log in to reply
 

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