leetcode 004 —— Median of Two Sorted Arrays

来源:互联网 发布:人工智能顶级杂志 编辑:程序博客网 时间:2024/06/04 20:06

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:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        int *a=new int[m+n];                    memcpy(a,A,sizeof(int)*m);          memcpy(a+m,B,sizeof(int)*n);                    sort(a,a+n+m);                    double median=(double) ((n+m)%2? a[(n+m)>>1]:(a[(n+m-1)>>1]+a[(n+m)>>1])/2.0);                    delete a;                    return median;      }};

方法二:可以用一个计数器,记录当前已经找到第m 大的元素了。同时我们使用两个指针pA 和pB,分别指向A 和B 数组的第一个元素,使用类似于merge sort 的原理,如果数组A 当前元素小,那么pA++,同时m++;如果数组B 当前元素小,那么pB++,同时m++。最终当m 等于k 的时候,就得到了我们的答案,O(k) 时间,O(1) 空间。但是,当k 很接近m + n 的时候,这个方法还是O(m + n) 的。
方法三:


0 0
原创粉丝点击