LeetCode矩陣類訓練

LeetCode矩陣類訓練

4. Median of Two Sorted Arrays
描述:
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
解:
主要是歸併排序法【意會吧】。

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        res = []
        l = 0
        r = 0
        while l<len(nums1) and r<len(nums2):
            if nums1[l] < nums2[r]:
                res.append(nums1[l])
                l += 1
            else:
                res.append(nums2[r])
                r += 1
        res += list(nums1[l:])
        res += list(nums2[r:])
        k = len(res)
        if k%2 == 0:
            med = (res[k/2-1]+res[k/2])/2.0
        else:
            med = float(res[k/2])
        return med
  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章