Is this a "hard" problem? [Divide and conquer in golang, 16ms]


  • 0

    It's seems to me a "medium" or even easier problem.. just divide and conquer and submit! haha!

    Please tell me if my code can be any better.

    func mergeKLists(lists []*ListNode) *ListNode {
    	if len(lists) == 0 {
    		return nil
    	}
    
    	return mergeMoreThanOneLists(lists)
    }
    
    func mergeMoreThanOneLists(lists []*ListNode) *ListNode {
    	length := len(lists)
    	half := length / 2
    
    
    	if length == 1 {
    		return lists[0]
    	}
    
    	if len(lists) == 2 {
    		var head, follow *ListNode
    		l1, l2 := lists[0], lists[1]
    
    		if l1 == nil {
    			return l2
    		}
    
    		if l2 == nil {
    			return l1
    		}
    
    		if l1.Val > l2.Val {
    			head, follow = l2, l2
    			l2 = l2.Next
    		} else {
    			head, follow = l1, l1
    			l1 = l1.Next
    		}
    
    		for {
    			if l1 == nil {
    				follow.Next = l2
    				break
    			}
    
    			if l2 == nil {
    				follow.Next = l1
    				break
    			}
                
    			if l1.Val > l2.Val {
    				follow.Next = l2
    				l2 = l2.Next
    			} else {
    				follow.Next = l1
    				l1 = l1.Next
    			}
    			follow = follow.Next
    		}
    		return head
    	}
    
    	return mergeMoreThanOneLists([]*ListNode{
    		mergeMoreThanOneLists(lists[half:]),
    		mergeMoreThanOneLists(lists[:half]),
    	})
    }
    

    By the way, who can tell me why I rarely see golang solutions in discuss ?_?


  • 0
    A
    This post is deleted!

Log in to reply
 

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