寻找两个正序数组的中位数02
作者:互联网
昨天写题有点懵,回去想了一下有些不必要的操作,进行简单的优化
代码展示
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
double targ = 0;
vector<int> nums3;
if (nums2.size() != 0 && nums1.size() != 0)
{
bool f = true;
unsigned int i = 0, j = 0;
while (f)
{
if (nums1.at(i) < nums2.at(j))
{
nums3.push_back(nums1.at(i));
i++;
if (i == nums1.size())
{
for (j; j < nums2.size(); j++)
{
nums3.push_back(nums2.at(j));
}
f = false;
}
}
else
{
nums3.push_back(nums2.at(j));
j++;
if (j == nums2.size())
{
for (i; i < nums1.size(); i++)
{
nums3.push_back(nums1.at(i));
}
f = false;
}
}
}
}
else
{
nums3 = nums1.size() > nums2.size() ? nums1 : nums2;
}
if (nums3.size() == 0)
{
targ = 0;
return 0;
}
if (nums3.size() % 2 == 0)
{
targ = nums3.at(nums3.size() / 2) +
nums3.at(nums3.size() / 2 - 1);
targ = (double)targ / 2;
}
else {
targ = (double)nums3.at(nums3.size() / 2);
}
return targ;
}
};
改动
把数组nums2加入到nums1去掉,删除多余变量
标签:02,正序,targ,中位数,back,nums3,nums1,nums2,size 来源: https://blog.csdn.net/L_30629685/article/details/115413084