# 4.、Median of Two Sorted Arrays(两个有序序列的中位数)

leetcode刷题记录 专栏收录该内容
8 篇文章 0 订阅

C++：

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int last = 0,cur = 0;
int mid = (len1+len2)/2;

int k = 0,i = 0,j = 0;
while(k <= mid)
{
last = cur;
if(i == len1)
{
cur = nums2[j];
j++;
}
else if(j == len2)
{
cur = nums1[i];
i++;
}
else if(nums1[i] < nums2[j])
{
cur = nums1[i];
i++;
}
else
{
cur = nums2[j];
j++;
}
k++;
}
return (len1+len2)%2?cur:double(last+cur)/2;
}

python:

    def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
last = 0
cur  = 0
len1 = len(nums1)
len2 = len(nums2)
mid  = (len1 + len2)/2
i = 0
j = 0
k = 0
while(k <= mid):
last = cur
if i == len1:
cur = nums2[j]
j = j + 1
elif j == len2:
cur = nums1[i]
i = i + 1
elif nums1[i] < nums2[j]:
cur = nums1[i]
i = i + 1
else:
cur = nums2[j]
j = j + 1
k = k + 1
if (len1+len2)%2:
return cur
else:
return (last+cur)/2.0

• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

03-04 436
09-20 455
04-09 3万+
09-20 301