您的位置:首页 > 其它

leetcode: 4. Median of Two Sorted Arrays

2017-10-31 10:00 351 查看

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)).
#
# 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


AC

class Solution():
def findMedianSortedArrays(self, nums1, nums2):
nums = sorted(nums1 + nums2)
if len(nums) == 1:
return nums[0]
if len(nums) % 2:
return nums[len(nums) // 2]
else:
return (nums[len(nums)//2 - 1] + nums[len(nums)//2]) / 2.0

if __name__ == '__main__':
assert Solution().findMedianSortedArrays([10], []) == 10
assert Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) == 4
assert Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) == 3.5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: