LeetCode | 4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

Description

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)).
You may assume nums1 and nums2 cannot be both empty.

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

Solution: (Java)
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int index1 = 0, index2 = 0, medianIndex, count = 0;
        medianIndex = (nums1.length + nums2.length) / 2;
        int[] arr = new int[medianIndex + 1];
        while (index1 < nums1.length && index2 < nums2.length) {
            if (nums1[index1] <= nums2[index2]) {
                arr[count] = nums1[index1];
                index1++;
            } else {
                arr[count] = nums2[index2];
                index2++;
            }
            count++;
            if (count > medianIndex)
                break;
        }
        if (count <= medianIndex) {
            if (index1 == nums1.length) {
                while (index2 < nums2.length) {
                    arr[count] = nums2[index2];
                    index2++;
                    count++;
                    if (count > medianIndex)
                        break;
                }
            } else {
                while (index1 < nums1.length) {
                    arr[count] = nums1[index1];
                    index1++;
                    count++;
                    if (count > medianIndex)
                        break;
                }
            }
        }
        if ((nums1.length + nums2.length) % 2 == 0)
            return (arr[medianIndex-1] + arr[medianIndex])*1.0 / 2;
        else
            return arr[medianIndex];
    }
}
思路

本题的代码还可以再稍微精简一下,不过这样也比较简单易懂吧,先得到中位数的索引位置,然后从两个数组中,依次把较小的数往新的数组填充,一直到中位数的位置,那么新数组的最后一个或者最后两个数的平均值即为中位数。

二分查找

其实上面的思路是不符合题目规定的时间复杂度的,有一种合适的思路是二分查找(binary search),后续补充…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值