leetcode - Median of Two Sorted Arrays

来源:互联网 发布:情义知多少 编辑:程序博客网 时间:2024/04/18 11:45

There are two sorted arrays A and B 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)).

class Solution {public:    int findKth(int A[], int m, int B[], int n, int k) {        int l = k - 1 - std::min(k - 1, n), r = std::min(k, m);        while (l <= r) {            int i = l + ((r - l) >> 1);            int j = k - 1 - i;            if (i >= 0 && i < m && (j >= n || A[i] <= B[j]) && (j == 0 || B[j-1] <= A[i]))                return A[i];            else if (j >= 0 && j < n && (i >= m || B[j] <= A[i]) && (i == 0 || A[i-1] <= B[j]))                return B[j];            if (j >= n || A[i] < B[j]) l = i + 1;            else r = i - 1;        }    }    double findMedianSortedArrays(int A[], int m, int B[], int n) {        if ((m + n) & 1) return findKth(A, m, B, n, ((m + n) >> 1) + 1);        else return (findKth(A, m, B, n, (m + n) >> 1) + findKth(A, m, B, n, ((m + n) >> 1) + 1)) * 0.5;    }};


0 0
原创粉丝点击