[Leetcode] Median of Two Sorted Arrays

大致思路:

先寻找每个数组的中位数,因为是排好顺序的数组,因此,可以在O(1)时间内找到。然后,比较这两个数字的大小。如果A的中位数大于B的中位数,则在A的前半个数组和B的后半个数组中寻找; 反之,在B的前半个数组和A的后半个数组寻找。根据递归方程,解得时间复杂度是O(lg(n)).

 

A general version:

Find the Kth element of two sorted arrays A[] and B[].

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstdlib>
 4 using namespace std;
 5 
 6 int findKthElem(int A[], int aBeg, int aEnd, int B[], int bBeg, int bEnd, int k){
 7 
 8     //cout << aBeg << " | " << aEnd << " | " << bBeg << " | " << bEnd << " | " << k << endl;
 9 
10     if(aBeg > aEnd){
11         return B[bBeg + k - 1];
12     }
13     if(bBeg > bEnd){
14         return A[aBeg + k - 1];
15     }
16 
17     int aMid = (aBeg + aEnd) >> 1;
18     int bMid = (bBeg + bEnd) >> 1;
19     int len = aMid - aBeg + bMid - bBeg + 2;
20 
21     if(len > k){
22         if(A[aMid] < B[bMid]){
23             return findKthElem(A, aBeg, aEnd, B, bBeg, bMid-1, k);
24         }
25         else{
26             return findKthElem(A, aBeg, aMid-1, B, bBeg, bEnd, k);
27         }
28     }
29     else{
30         if(A[aMid] < B[bMid]){
31             return findKthElem(A, aMid+1, aEnd, B, bBeg, bEnd, k-(aMid-aBeg+1));
32         }
33         else{
34             return findKthElem(A, aBeg, aEnd, B, bMid+1, bEnd, k-(bMid-bBeg+1));
35         }
36     }
37 }
38 
39 int main()
40 {
41     const int ALen = 11;
42     const int BLen = 5;
43 
44     int apos = 0;
45     int bpos = 0;
46     int A[ALen];
47     int B[ALen];
48 
49     //生成两个递增数组A 和 B
50     for (int i = 1; i <= ALen + BLen; ++i)
51     {
52         if (apos >= ALen)
53         {
54             B[bpos++] = i;
55         }
56         else if (bpos >= BLen)
57         {
58             A[apos++] = i;
59         }
60         else
61         {
62             if (rand()%2 == 1)
63             {
64                 A[apos++] = i;
65             }
66             else
67             {
68                 B[bpos++] = i;
69             }
70         }
71     }
72 
73     //输出A和B的内容
74     for (int i = 0; i < ALen; ++i)
75     {
76         cout <<A[i] <<" ";
77     }
78     cout <<endl;
79     for (int i = 0; i < BLen; ++i)
80     {
81         cout <<B[i] <<" ";
82     }
83     cout <<endl;
84 
85     //验证每个K是不是正解
86     for (int i = 1; i <= ALen + BLen; ++i)
87     {
88         cout << i <<" : "<<findKthElem(A, 0 , ALen - 1, B, 0 , BLen - 1, i)<<endl;
89     }
90 
91     return 0;
92 }

 

参考:

http://blog.csdn.net/realxie/article/details/8078043

http://doudouclever.blog.163.com/blog/static/175112310201151584521268/

http://www.cnblogs.com/etcow/archive/2012/09/26/2704855.html

posted on 2013-03-04 23:06  龙豆  阅读(1188)  评论(0编辑  收藏  举报

导航