您的位置:首页 > 编程语言 > Java开发

(leetcode)4.两个有序数列中间的第n个数 Median of Two Sorted Arrays--Java

2017-04-24 14:01 351 查看
There are two sorted arrays nums1 and nums2 of size m and n respectively.

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

public class Solution {

    public double findMedianSortedArrays(int A[], int B<
4000
/span>[]) {

        int len = A.length + B.length;

        if (len % 2 == 1) {

            return findKth(A, 0, B, 0, len / 2 + 1);

        }

        return (

            findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)

        ) / 2.0;

    }

    // 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) {

                        return B[B_start + k - 1];

                }

                if (B_start >= B.length) {

                        return A[A_start + k - 1];

                }

                if (k == 1) {

                        return Math.min(A[A_start], B[B_start]);

                }

               

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

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

                }
       
}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: