给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数
https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
示例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
提示:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Java解法
思路:
- 最简单的处理应该就是先合并再查找
package sj.shimmer.algorithm.y2021;
import java.util.Arrays;
/**
* Created by SJ on 2021/3/15.
*/
class D49 {
public static void main(String[] args) {
System.out.println(findMedianSortedArrays(new int[]{1,2},new int[]{3,4}));
System.out.println(findMedianSortedArrays(new int[]{0,0},new int[]{0,0}));
System.out.println(findMedianSortedArrays(new int[]{},new int[]{1}));
System.out.println(findMedianSortedArrays(new int[]{2},new int[]{}));
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1 == null&&nums2==null) {
return 0;
}else if (nums1==null){
int len = nums2.length;
if (len%2==0) {
return (nums2[len / 2] + nums2[len / 2 + 1]) / 2;
}else {
return nums2[len / 2];
}
}else if (nums2==null){
int len = nums1.length;
if (len%2==0) {
return (nums1[len / 2] + nums1[len / 2 + 1]) / 2;
}else {
return nums1[len / 2];
}
}
int[] merge = merge(nums1, nums2);
Arrays.sort(merge);
int length = merge.length;
if (length %2==1) {
return merge[length/2];
}
return (merge[length/2]+merge[length/2-1])/2.0;
}
public static int[] merge(int[] left, int[] right) {
int lLength = left.length;
int rLength = right.length;
int[] results = new int[lLength + rLength];
int length = results.length;
for (int l = 0, r = 0, i = 0; i < length; i++) {
if (l > lLength - 1) {
results[i] = right[r++];
} else if (r > rLength - 1) {
results[i] = left[l++];
} else {
if (left[l] > right[r]) {
results[i] = right[r++];
} else {
results[i] = left[l++];
}
}
}
return results;
}
}
image
官方解
-
二分查找
- 归并查找,我的处理
- 双指针移动
- 归纳处理,脑子乏了有点看不透后续再刷下
-
时间复杂度:
-
空间复杂度:
网友评论