Question:
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
Answer:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int i = 0,j = 0,t;
double n = (nums1.size()+nums2.size())/2.0,s=0,ss=0;
for(int k=0;k<=floor(n);k++)
{
if(j == nums2.size())
{
t = nums1[i];
i++;
}
else if(i == nums1.size()||nums1[i]>nums2[j])
{
t = nums2[j];
j++;
}
else
{
t = nums1[i];
i++;
}
if(k>=ceil(n-1))
{
s+=t;
ss+=1.0;
}
}
return s/ss;
}
};
Key:
else if(i == nums1.size()||nums1[i]>nums2[j])
注意 ||
连接条件的顺序,前一条件为真,后面的条件就不判断,避免了数组越界。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于