1. 程式人生 > >【LeetCode 4】Median of Two Sorted Arrays(Python)

【LeetCode 4】Median of Two Sorted Arrays(Python)

Problem:

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

Solutions:

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        cache = []
        len_nums1 = len(nums1)
        len_nums2 = len(nums2)
        mid_idx = []
        total_len = len_nums1+len_nums2
        if total_len%2==0:
            mix_idx.extend([int(total_len/2)-1,int(total_len/2)])
        else:
            mid_idx.append(int(total_len/2))
        i1,i2=0,0
        for i in range(mid_idx[0]+1):
            if i1>=len_nums1:
                cache.append(nums2[i2+mid_idx[0]-i-1])
                if len(mix_idx)==2:
                    cache.append(nums2[i2+mid_idx[1]-i-1])
                break
            elif i2>=len_nums2:
                cache.append(nums1[i1+mid_idx[0]-i-1])
                if len(mix_idx)==2:
                    cache.append(nums1[i1+mid_idx[1]-i-1])
                break
            else:
                if nums1[i1]>=nums2[i2]:
                    i2+=1
                    if i==mid_idx[0]:
                        cache.append(nums2[i2-1])
                        if len(mid_idx)==2:
                            cache.append(min(nums1[i1],nums2[i2]))
                        break
                else:
                    i1+=1
                    if i==mid_idx[0]:
                        cache.append(nums1[i1-1])
                        if len(mid_idx)==2:
                            cache.append(min(nums1[i1],nums2[i2]))
                        break
        return sum(cache)/len(cache)

這個解決方法有些複雜。。