Straight forward Merge Sort solution in Python


  • 0
    C
    class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        def mergeSort(nums):
            if len(nums)<2:
                return nums
            else:
                mid=len(nums)/2
                left=mergeSort(nums[:mid])
                right=mergeSort(nums[mid:])
                return unimerge(left, right, False)
            
        def unimerge(left, right, output):
            temp=[]
            while left and right:
                if left[0]>right[0]:
                    temp.append(right.pop(0))
                elif left[0]<right[0]:
                    temp.append(left.pop(0))
                else:
                    temp.append(left.pop(0))
                    if output:
                        self.res.append(right.pop(0))
                    else:
                        right.pop(0)
            if left: temp+=left
            if right: temp+=right
            return temp
        
        self.res=[]
        test=unimerge(mergeSort(nums1),mergeSort(nums2),True)
        return self.res

Log in to reply
 

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