[Leetcode]Median of two sorted array

来源:互联网 发布:龙珠gt战斗力官方数据 编辑:程序博客网 时间:2024/05/16 14:17

[题目]

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

[分析]


[code] from nineChapter

public double findMedianSortedArrays(int A[], int B[]) {        int len = A.length + B.length;   //AB一起总共的长度        if (len % 2 == 0) {     //如果总长度是偶数            return (findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)) / 2.0 ;  //那么分表找A,B 的中前长度值和中后长度值,然后取中间        } else {            return findKth(A, 0, B, 0, len / 2 + 1);  //如果直接是奇数的,那么直接返回中间值就好了。        }    }        // find kth number of two sorted array    public static int findKth(int[] A, int A_start, int[] B, int B_start, int k){if(A_start >= A.length)   //如果A的起始已经大于A 的总长度了,那么直接返回B的开始 + k -1位置的值return B[B_start + k - 1];  if(B_start >= B.length)   //同理,对于B,加入已经到头了,return A[A_start + k - 1];//返回A开始的位置加k.if (k == 1)  //如果k==1,return Math.min(A[A_start], B[B_start]);//返回A,B开头最大的那个int A_key = A_start + k / 2 - 1 < A.length            ? A[A_start + k / 2 - 1]            : Integer.MAX_VALUE;int B_key = B_start + k / 2 - 1 < B.length            ? B[B_start + k / 2 - 1]            : Integer.MAX_VALUE; if (A_key < B_key) { //如果A的值小于B,搜索A的后半部分,对于B不用动,整体长度减半return findKth(A, A_start + k / 2, B, B_start, k - k / 2);} else {return findKth(A, A_start, B, B_start + k / 2, k - k / 2);}}




0 0
原创粉丝点击