
最容易想到的解法就是暴力解法了,直接合并数组,然后返回数组的中位数就行了
时间复杂度:遍历全部数组O(m+n)
空间复杂度:创建了一个数组O(m+n)
显然时间复杂度是不满足题目要求的
- 代码:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] all = new int[nums1.length + nums2.length];
int index = 0;
int i = 0;
int j = 0;
double res = 0.0;
while(true){
if(i == nums1.length && j < nums2.length){
for(int m = j;m < nums2.length;m++){
all[index++] = nums2[m];
}
break;
}else if(i < nums1.length && j == nums2.length){
for(int m = i;m < nums1.length;m++){
all[index++] = nums1[m];
}
break;
}else if(i == nums1.length && j == nums2.length){
break;
}
if(nums1[i] < nums2[j]){
all[index++] = nums1[i++];
}else{
all[index++] = nums2[j++];
}
}
int l = all.length/2;
if((all.length % 2) == 0){
res = (all[l] + all[l-1])/2.0;
}else if((all.length % 2) == 1){
res = all[l];
}
return res;
}
}

网友评论