题目
题目来源leetcode
有两个数组,长度各为m, n,且数组内数据排序是正序(由小到大),合并这两个数组成新的正序数组,并求出他们的中位数。要求O(log(m+n))
结果
merge two list:
1 4 89 1234
0 3 999 1000
res: 0 1 3 4 89 999 1000 1234
middle num: 46.5
merge two list:
1 4 89 1234
0 3 1000
res: 0 1 3 4 89 1000 1234
middle num: 4
结果
题目实则考的是如何合并两个数组,考虑o(log(m+n)),其实使用二叉树插入,是相当快的. 以下不一定对,但可作为参考
#include <iostream>
#include <vector>
#include <set>
double _find_mid_num(const std::vector<int>& a, const std::vector<int>& b, std::vector<int>& res_list) {
std::set<int> merge_list;
for (auto i : a)
merge_list.insert(i);
for (auto i : b)
merge_list.insert(i);
std::size_t count = merge_list.size();
double res = 0;
res_list.resize(a.size() + b.size());
std::size_t i = 0;
for (auto it : merge_list) {
res_list[i++] = it;
}
if (count % 2 == 0) {
// 偶数
std::size_t target_index = count / 2 - 1;
res = double(res_list[target_index] + res_list[target_index + 1]) * 0.5;
}
else {
// 奇数
std::size_t target_index = count / 2;
res = double(res_list[target_index]);
}
return res;
}
void output_res(const std::vector<int>& a, const std::vector<int>& b, const std::vector<int>& res_lst, double res) {
std::cout << std::endl << "merge two list:" << std::endl;
for (auto it : a) std::cout << " " << it;
std::cout << std::endl;
for (auto it : b) std::cout << " " << it;
std::cout << std::endl << " res: ";
for (auto it : res_lst) std::cout << " " << it;
std::cout << std::endl << "middle num: " << res;
}
void find_mid_num(){
{
std::vector<int> a = { 1,4, 89, 1234 }, b = { 0, 3, 999, 1000 }, res;
double mid = _find_mid_num(a, b, res);
output_res(a, b, res, mid);
}
{
std::vector<int> a = { 1,4, 89, 1234 }, b = { 0, 3, 1000 }, res;
double mid = _find_mid_num(a, b, res);
output_res(a, b, res, mid);
}
}