思路:
- 将两个有序数组排序放在临时数组中
- 判断临时总元素个数,如果为奇数,直接取中间的数返回。如果是偶数,则将中间两个数除以2.0返回即可。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int i = 0, j= 0,start = 0,len = nums1.length+ nums2.length;
int [] res = new int[nums1.length+ nums2.length];
//将两个数组元素较小的放入临时数组中,
while (i< nums1.length && j< nums2.length){
if(nums1[i] >= nums2[j]){
res[start++] = nums2[j++];
}else{
res[start++] = nums1[i++];
}
}
//将剩余节点放到后面
if (i < nums1.length) {
for(;i<nums1.length;i++){
res[start++] = nums1[i];
}
}
if (j < nums2.length) {
for(;j<nums2.length;j++){
res[start++] = nums2[j];
}
}
//判断总元素个数为奇数还是偶数
if(len%2 == 1){
// 奇数, 直接取中间的就可以了
return res[len/2];
}else{
//偶数,取两边然后除以2
return (res[len / 2]+res[(len / 2)-1])/2.0;
}
}
}