LeetCode: [4] 寻找两个正序数组的中位数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
nums = []
while nums1 and nums2:
if nums1[0] > nums2[0]:
nums.append(nums2.pop(0))
else:
nums.append(nums1.pop(0))
if nums1:
nums.extend(nums1)
if nums2:
nums.extend(nums2)

length = len(nums)
mid = length // 2
if length % 2 != 0:
return nums[mid]
return (nums[mid - 1] + nums[mid]) / 2