LeetCode- 寻找两个正序数组的中位数题解
题目:给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
示例一: 输入:nums1 = [1,3], nums2 = [2] 输出:2.00000 解释:合并数组 = [1,2,3] ,中位数 2
示例二:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
题目地址:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
个人答案:
#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
vector<int> v;
int num1[] = { 1,2 }, num2[] = { 3 };
int i = sizeof(num1) / 4;
for (int j = 0; j < i; j++) {
v.push_back(num1[j]);
}
i = sizeof(num2) / 4;
for (int j = 0; j < i; j++) {
v.push_back(num2[j]);
}
sort(v.begin(), v.end());
int NumBer = v.size();
cout << NumBer << endl;;
if (NumBer % 2 != 0) {
int OutCome = (NumBer / 2);
cout << v[OutCome];
}
else {
int OutCome1 = (NumBer / 2);
int OutCome2 = (NumBer / 2) - 1;
double EndResult = (v[OutCome1] + v[OutCome2]) / 2.0;
cout << EndResult;
}
}
祝每天开心
评论已关闭