LeetCode OJ: Median of Two Sorted Arrays

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)).

求中位数,思想跟归并的一样了,只是不用记录所有的数,只需要记录中间位置的记录,对奇数长度与偶数长度的情况处理下就好。

代码如下:

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(int A[], int m, int B[], int n) {
 4         int mid = (m + n) / 2;
 5         int rest = (m + n) % 2;
 6         int i = 0, j = 0, k = 0;
 7         int pre, cur = 0;
 8         while (i < m && j < n && k <= mid) {
 9             if (A[i] < B[j]) {
10                 pre = cur;
11                 cur = A[i];
12                 k++;
13                 i++;
14             } else {
15                 pre = cur;
16                 cur = B[j];
17                 k++;
18                 j++;
19             }
20         }
21         while (k <= mid && i < m) {
22             pre = cur;
23             cur = A[i];
24             i++;
25             k++;
26         }
27         while (k <= mid && j < n) {
28             pre = cur;
29             cur = B[j];
30             j++;
31             k++;
32         }
33         if (rest == 0) {
34             return 0.5 * (pre + cur);
35         } else {
36             return cur;
37         }
38     }
39 };

 

posted @ 2014-03-23 01:32  flowerkzj  阅读(142)  评论(0编辑  收藏  举报