您的位置:首页 > 其它

【leetcode】4. Median of Two Sorted Arrays

2017-08-22 18:17 387 查看
/**
 * There are two sorted arrays nums1 and nums2 of size m and n respectively.

    Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

    Example 1:

    nums1 = [1, 3]
    nums2 = [2]

    The median is 2.0

    Example 2:

    nums1 = [1, 2]
    nums2 = [3, 4]

    The median is (2 + 3)/2 = 2.5
 *
 */
class Solution {

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length1 = nums1.length;
int length2 = nums2.length;
int length = length1 + length2;
int mid = (length) / 2;
// 合并数组
int[] nums = new int[length];
double d = 0.0;
if (length1 == 0) {
if (length2 != 0) {
nums = nums2;
} else {
return d;
}
} else {
if (length2 != 0) {
int i = 0, j = 0, k = 0;
while (i < length1 && j < length2)
if (nums1[i] <= nums2[j]) {
nums[k++] = nums1[i++];
} else {
nums[k++] = nums2[j++];
}
while (i < length1)
nums[k++] = nums1[i++];
while (j < length2)
nums[k++] = nums2[j++];
} else {
nums = nums1;
}
}
// 奇偶性
boolean even = length % 2 == 0 ? true : false;
if (length > 0) {
if (even) {
d = (double) (nums[mid - 1] + nums[mid]) / 2;
} else {
d = nums[mid];
}
}
return d;
}
}

思路:先判断各自的长度、最终的奇偶性,然后归并,最后找到中间的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: