# Leetcode 4 寻找两个正序数组的中位数

• 将两个有序链表合并，然后根据中位数定义查找
• 分段折半查找

public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
double ans = s.findMedianSortedArrays(new int[]{1,3,4}, new int[]{2});
System.out.println(ans);
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// 双指针合并数组
int len1 = nums1.length, len2 = nums2.length, n = len1 + len2;
int[] res = new int[n];
int p = 0, q = 0, k = 0;
if(len1 == 0 && len2 != 0){
res = nums2;
}else if(len1 != 0 && len2 == 0){
res = nums1;
}else {
while (p < len1 && q < len2) {
if (nums1[p] > nums2[q]) {
res[k++] = nums2[q++];
} else if (nums1[p] == nums2[q]) {
res[k++] = nums2[q++];
res[k++] = nums1[p++];
} else {
res[k++] = nums1[p++];
}
}
while (p < len1) {
res[k++] = nums1[p++];
}
while (q < len2) {
res[k++] = nums2[q++];
}
int i = 0;
while (i++ < res.length) {
System.out.print(res[i - 1] + ",");
}
}
if (res.length % 2 == 0) {
return (double) (res[res.length / 2] + res[(res.length / 2) - 1]) / 2;
} else {
return (double) res[(res.length - 1) / 2];
}
}
}

posted @ 2021-04-12 15:11  YC-L  阅读(4)  评论(0编辑  收藏