题目描述:
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
输入: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
解题思路:
我的思想很简单,就是把两个数组整合,排序成一个数组,这个步骤在while循环中很简单的就实现了,然后就是如果这个整合好的新数组大小是一个奇数,就直接找它的中位数,不过要记住数组是从0开始的,如果是偶数就找中间的两个数,然后求和,再除二。最后返回。
代码很少。
代码部分:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2){
int x=0;
int d=0;
int index=0;
int i=nums1.size();
int j=nums2.size();
int nums3[i+j];
while(x<i&&d<j){//整合排序成一个新数组
if(nums1[x]<nums2[d]){
nums3[index++]=nums1[x++];
}
else{
nums3[index++]=nums2[d++];
}
}
while (x < i) {
nums3[index++] = nums1[x++];
}
while (d < j) {
nums3[index++] = nums2[d++];
}
if(index%2==1){//找奇数
float g=nums3[(index+1)/2-1];
return g;
}
else{//找偶数
float s=(nums3[(index/2)-1]+nums3[index/2]);
float k;
k = s / 2;
return k;
}
}
};