题目来源:力扣(LeetCode)
链接:https://leetcode-/problems/median-of-two-sorted-arrays
题目描述
给定两个大小为 m 和 n 的正序(从小到大)数组nums1
和nums2
。请你找出并返回这两个正序数组的中位数。
输入样例
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
示例 3:
输入:nums1 = [0,0], nums2 = [0,0]
输出:0.00000
示例 4:
输入:nums1 = [], nums2 = [1]
输出:1.00000
示例 5:
输入:nums1 = [2], nums2 = []
输出:2.00000
解题思路
将两个数组合并成一个数组,去中间的两个数或者一个数。
解题代码
//#include <vector>//#include <iostream>using namespace std;class Solution {public:double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) {int n1 = nums1.size();int n2 = nums2.size();int n = n1 + n2;int mergeVector[n];int index = 0;int index1 = 0;int index2 = 0;while (index <= n/2 && index1 < n1 && index2 < n2) {if (nums1[index1] < nums2[index2]) {mergeVector[index] = nums1[index1];index1++;} else {mergeVector[index] = nums2[index2];index2++;}index++;}while (index <= n/2 && index1 < n1) {mergeVector[index] = nums1[index1];index1++;index++;}while (index <= n/2 && index2 < n2) {mergeVector[index] = nums2[index2];index2++;index++;}if (n%2 ==0){return ((double) (mergeVector[n/2]+mergeVector[n/2-1]))/2;} else{return mergeVector[n/2];}}};//int main() {//// Solution solution;// vector<int> nums1;// vector<int> nums2;// nums2.push_back(1);// nums2.push_back(2);// nums1.push_back(3);//// double res = solution.findMedianSortedArrays(nums1,nums2);// cout << res;// return 0;////}