leetcode: 4. Median of Two Sorted Arrays (java)

题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/

题目:

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)).


解析:一开始采用了归并排序的思想来解这道题,思想简单,但是复杂度为O(m+n);

后来借鉴了别人的思路:http://blog.csdn.net/linhuanmars/article/details/19905515


java 代码实现:

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int length = nums1.length + nums2.length;
        if (length%2 == 1){
            return recrusive(nums1, nums2, 0, nums1.length-1, 0, nums2.length-1, length/2 + 1);
        } else {
            return (recrusive(nums1, nums2, 0, nums1.length-1, 0, nums2.length-1, length/2)+recrusive(nums1, nums2, 0, nums1.length-1, 0, nums2.length-1, length/2 + 1))/2.0;
        }
    }


    public double recrusive(int[] A, int[] B, int i, int i2, int j, int j2, int k){
        int m = i2-i+1;
        int n = j2-j+1;
        if (m > n) return recrusive(B, A, j, j2, i, i2, k);
        if (m == 0) {
            return B[j+k-1];
        }
        if (k == 1){
            return Math.min(A[i], B[j]);
        }
        int posA = Math.min(k/2, m);
        int posB = k-posA;
        if(A[i+posA-1] == B[j+posB-1]){
            return A[i+posA-1];
        }else if (A[i+posA-1] < B[j+posB-1]){
            return recrusive(A, B, i+posA, i2, j, j+posB-1, k-posA);
        }else {
            return recrusive(A, B, i, i+posA-1, j+posB, j2, k-posB);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值