LeetCode

来源:互联网 发布:贵金属交易软件排行 编辑:程序博客网 时间:2024/06/06 02:25

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


一个递归的思想,时间复杂度O(log(m+n))

每次二分两个数组,当a[i-1] > b[j-1]的时候,说明第k大的数字在a的左边和b的右边;否则,第k大的数字在a的右边b的左边。

就这样递归下去,直到求出值。

class Solution {public:    double findMedianSortedArrays(int a[], int m, int b[], int n) {        int l = (m + n + 1) >> 1;        int r = (m + n + 2) >> 1;        return (solve(a, m, b, n, l) + solve(a, m, b, n, r)) / 2.0;    }        int solve(int a[], int m, int b[], int n, int k) {        if (m > n) return solve(b, n, a, m, k);        if (m == 0) return b[k-1];        if (k == 1) return min(a[0], b[0]);                int i = min(m, k / 2), j = min(n, k / 2);        if (a[i - 1] > b[j - 1])             return solve(a, m, b + j, n - j, k - j);        else             return solve(a + i, m - i, b, n, k - i);    }};