Median of Two Sorted Arrays(C++)
程序员文章站
2022-07-15 10:46:49
...
计算两个数组连接到一起后的中位数。
我的思路是这样的:将两个数组合并为一个数组,然后找到新数组的中位数,这个数即为我们想要得到的中位数。
具体的代码如下:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> num;
double aver;
int length;
int i = 0;
if (nums1.size() == 0&& nums2.size()) {
length = nums2.size();
for (int i = 0; i < nums2.size(); i++) {
num.push_back(nums2[i]);
}
}
else if (nums2.size() == 0&& nums1.size()) {
length = nums1.size();
for (int i = 0; i < nums1.size(); i++) {
num.push_back(nums1[i]);
}
}
else if (nums1.size() == 0 && nums2.size() == 0) {
length = 0;
num = {};
}
else {
length = nums1.size() + nums2.size();
if (nums1[nums1.size() - 1] < nums2[0]) {
for (int i = 0; i < nums1.size(); i++) {
num.push_back(nums1[i]);
}
for (int i = 0; i < nums2.size(); i++) {
num.push_back(nums2[i]);
}
}
else if (nums2[nums2.size() - 1] < nums1[0]) {
for (int i = 0; i < nums2.size(); i++) {
num.push_back(nums2[i]);
}
for (int i = 0; i < nums1.size(); i++) {
num.push_back(nums1[i]);
}
}
else {
int j = 0;
nums1.push_back(99999);
for (int i = 0; i < nums2.size(); i++) {
while (nums2[i] >= nums1[j]) {
num.push_back(nums1[j]);
j++;
}
num.push_back(nums2[i]);
}
if (j < nums1.size()-1) {
for (int i = j; i < nums1.size() - 1; i++) {
num.push_back(nums1[i]);
}
}
}
}
if (length == 0) {
aver = 0;
}
else {
if (length % 2 == 0) {
aver = (double)(num[length / 2] + num[length / 2 - 1]) / 2;
}
else {
aver = (double)num[length / 2];
}
}
return aver;
}
运行时间为:
推荐阅读
-
【LeetCode】4. Median of Two Sorted Arrays
-
1.Merge Two Sorted Arrays. py/合并排序有序数列
-
LeetCode 4. 两个排序数组的中位数 Median of Two Sorted Arrays
-
算法练习(3):Median of Two Sorted Arrays
-
LeetCode算法系列:4、Median of Two Sorted Arrays
-
4. Median of Two Sorted Arrays
-
4. Median of Two Sorted Arrays
-
【leetcode】4. Median of Two Sorted Arrays
-
【leetcode阿里题库】4. Median of Two Sorted Arrays
-
Median of Two Sorted Arrays(C++)