力扣LeetCode第4题寻找两个正序数组的中位数
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路: 这个题目被力扣定为困难,但是是很简单的,我本人认为这是一道简单难度的题。
1、定义两个变量记录两个数组此时遍历到的地方和一个记录拼接后正序的数组
2、比较两个变量所在位置的的数组的值,较小的那个放到数组中,并把较小数字的那个变量索引加1
3、当两个变量的索引到了最后一位结束循环
4、在这里由于2的影响,每次索引+1,如果一个数组已经到了索引最后位置,那么加1操作就会越界,即等于数组的长度,另一个数组还没遍历完,那么就得判断索引是否等于数组长度,如果是就把另一个数组的结果加到结果数组中。
5、最后两个索引都会等于数组的长度跳出循环,计算中位数(数组长度为偶数就是中间两个数的平均数)
代码:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int l1 = nums1.length;
int l2 = nums2.length;
int lr = l1 + l2;
int res[] = new int[lr];
int n1 = 0;
int n2 = 0;
int r = 0;
while (n1 < l1 || n2 < l2) {
if (n1==l1) {
res[r] = nums2[n2];
n2++;
r++;
continue;
}
if (n2 == l2 ) {
res[r] = nums1[n1];
n1++;
r++;
continue;
}
if (nums1[n1] < nums2[n2]) {
res[r] = nums1[n1];
n1++;
} else {
res[r] = nums2[n2];
n2++;
}
r++;
}
if (lr % 2 == 0) {
return (res[lr/2] + res[lr/2 - 1]) / 2.0;
}
return res[lr / 2];
}
}
算法专题:力扣LeetCode算法专题