Median of Two Sorted Array---LeetCode

这道题比较直接的想法就是用Merge
Sorted Array这个题的方法把两个有序数组合并,当合并到第(m+n)/2个元素的时候返回那个数即可,而且不用把结果数组存起来。算法时间复杂度是O(m+n),空间复杂度是O(1)。因为代码比较简单,就不写出来了,跟Merge
Sorted Array比较类似,大家可以参照这个题目的解法。

接下来我们考虑有没有优化的算法。优化的思想来源于order statistics,在算法导论10.3节中提到。问题等价于求两个array的第k=(m+n)/2(假设m和n分别是两个数组的元素个数)大的数是多少。基本思路是每次通过查看两个数组的第k/2大的数(假设是A[k/2],B[k/2]),如果两个A[k/2]=B[k/2],说明当前这个数即为两个数组剩余元素的第k大的数,如果A[k/2]>B[k/2],
那么说明B的前k/2个元素都不是我们要的第k大的数,反之则排除A的前k/2个,如此每次可以排除k/2个元素,最终k=1时即为结果。总的时间复杂度为O(logk),空间复杂度也是O(logk),即为递归栈大小。在这个题目中因为k=(m+n)/2,所以复杂度是O(log(m+n))。比起第一种解法有明显的提高,代码如下:

    public double findMedianSortedArrays(int A[], int B[]) {
        if((A.length+B.length)%2==1)
            return helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1);
        else
            return (helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2)
                   +helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1))/2.0;
    }
    private int helper(int A[], int B[], int i, int i2, int j, int j2, int k)
    {
        int m = i2-i+1;
        int n = j2-j+1;
        if(m>n)
            return helper(B,A,j,j2,i,i2,k);
        if(m==0)
            return B[j+k-1];
        if(k==1)
            return Math.min(A[i],B[j]);
        int posA = Math.min(k/2,m);
        int posB = k-posA;
        if(A[i+posA-1]==B[j+posB-1])
            return A[i+posA-1];
        else if(A[i+posA-1]<B[j+posB-1])
            return helper(A,B,i+posA,i2,j,j+posB-1,k-posA);
        else
            return helper(A,B,i,i+posA-1,j+posB,j2,k-posB);
    }  

实现中还是有些细节要注意的,比如有时候剩下的数不足k/2个,那么就得剩下的,而另一个数组则需要多取一些数。但是由于这种情况发生的时候,不是把一个数组全部读完,就是可以切除k/2个数,所以不会影响算法的复杂度。

这道题的优化算法主要是由order statistics派生而来,原型应该是求topK的算法,这个问题是非常经典的问题,一般有两种解法,一种是用quick select(快速排序的subroutine),另一种是用heap。 复杂度是差不多的,有兴趣可以搜一下,网上资料很多,topK问题在海量数据处理中也是一个非常经典的问题,所以还是要重视。

(PS:由于题目要求时间复杂度为O(log(m+n))),说明在这个过程必须体现出二分查找,首先对于中位数必须有一个明确的认识,如果有奇数个数,那么中位数就是中间的那个数,如果有偶数个数,必须是中间两个数的平均数。再来考虑二分查找是依据什么二分呢?是根据中位数在两个数组中的位置来进行二分查找。如果一直未两个数组来二分,是查不到最终的结果。 
如果题目要求事件复杂度为O(n),这样就有很多种方法来实现这个问题,遍历两个数组,找到第k大,如果是多个数组,那么就可以使用heap作为辅助结构。这里的二分是以k/2

时间: 2024-10-09 00:16:51

Median of Two Sorted Array---LeetCode的相关文章

Median of Two Sorted Array leetcode java

题目: 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)). 题解: 首先我们先明确什么是median,即中位数. 引用Wikipedia对中位数的定义: 计算有限个数的数据的中位数的方法是:把所有的同类数据按照大小的顺序排列

【Leetcode】Median of Two Sorted Array II

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)). 非常经典的一个问题,如果直接查找中位数,即偶数约定向下取整,奇数就是严格的中位数,这个题目直接可以比较每个数组的mid来计算得到. 但是这个问题的需求更改为如果为偶数,则中

Find Minimum in Rotated Sorted Array leetcode

原题链接 直接贴代码,这道题是 search in rotated sorted array leetcode 的前面部分! 1 class Solution { 2 public: 3 int findMin(vector<int>& nums) { 4 if (nums.empty()) 5 return -1; 6 int res = find(nums, 0, nums.size()-1);//好神奇,第二个参数无论减或者不减1,都不影响该题的结果 7 if (res == -

Search in Rotated Sorted Array leetcode java

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no du

Merge Sorted Array leetcode java(回顾MergeTwoArray和MergeTwoLinkedList)

题目: Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B a

[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array

[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array 本题难度: Medium/Medium Topic: Binary Search Description Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you beforehand. (

Search in Rotated Sorted Array -- leetcode

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplic

天题系列:Median of Two Sorted Array

答案部分完全借鉴 http://www.cnblogs.com/springfor/p/3861890.html 以下是摘抄:“爱做饭的小莹子” 题目: 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)). 题解: 首先我们先

Find Minimum in Rotated Sorted Array leetcode java

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array. 解题思路: 首先假设一个sorted没有rotated的数组[1,2,3],假设我们通过一个

Remove Duplicates From Sorted Array leetcode java

算法描述: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example,Given input array