Just simple loop O(N*Max_Length_list)


  • 0
    S

    why cant we just loop it ?

    ...
    public class mergeKListst
    {
    //minheap is also a idea
    public ListNode MergeKListsMethod(ListNode[] lists)
    {
    ListNode answer = null;
    ListNode result = null;
    ListNode smallest = null;
    int smallIndex = 0;
    if (lists.Length == 0) return null;
    if (lists.Length == 1) return lists[0];
    do
    {
    smallest = lists[smallIndex];
    for (int i = 0; i < lists.Length; i++)
    {
    if (smallest == null)
    {
    smallest = lists[i];
    smallIndex = i;
    continue;
    }
    if (lists[i] != null)
    {
    if (smallest.val >= lists[i].val)
    {
    smallest = lists[i];
    smallIndex = i;
    }
    }

    			}
    			if (smallest != null)
    			{
    				lists[smallIndex] = lists[smallIndex].next;
    				if (result == null)
    				{
    					result = smallest;
    					answer = result;
    				}
    				else
    				{
    					result.next = smallest;
    					result = result.next;
    				}
    			}
    		} while (smallest != null);
    		return answer;
    	}
    }
    

    ...


Log in to reply
 

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