- 寻找两个正序数组的中位数
给定两个大小分别为 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
代码:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//思路:新建一个数组,长度为两数组总长度的一半 + 1(中位数),
//中位数就是新数组的最后一个值或者是倒数两个值的和的平均数
//新增变量,保存nums1和nums2的索引,比较两数组的值
int index1 = 0;
int index2 = 0;
int length1 = nums1.length;
int length2 = nums2.length;
double result = 0.0;
//两个数组长度都为0,直接返回0
if(length1 == 0 && length2 == 0){
return result;
}
//新数组
int newLength = ((length1 + length2) / 2) + 1;
int[] newArray = new int[newLength];
for(int i = 0; i < newLength; i++){
int num1;
int num2;
//数组1长度为0或者下标移动至尾部,直接计算数组2的中位数
if(length1 == 0 || index1 >= length1){
newArray[i] = nums2[index2];
index2++;
continue;
}else {
num1 = nums1[index1];
}
//数组2长度为0或者下标移动至尾部,直接计算数组1的中位数
if(length2 == 0 || index2 >= length2){
newArray[i] = nums1[index1];
index1++;
continue;
}else {
num2 = nums2[index2];
}
//判断两个值大小,小的保存到新数组,同时索引后移
if(num1 > num2){
newArray[i] = num2;
index2++;
}else{
newArray[i] = num1;
index1++;
}
}
result = (length1 + length2) % 2 == 0 ? (newArray[newLength - 1] + newArray[newLength - 2]) / 2.0:newArray[newLength - 1];
return result;
}
}