[LeetCode] Median of Two Sorted Arrays

This link has a very concise and fast solution based on binary search. Spend some time reading it and make sure you understand it. It is very helpful. 

Since the C++ interface of this problem has been updated, I rewrite the code below.

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
 4         int m = nums1.size(), n = nums2.size();
 5         if (m > n) return findMedianSortedArrays(nums2, nums1);
 6         int i, j, imin = 0, imax = m, half = (m + n + 1) / 2;
 7         while (imin <= imax) {
 8             i = (imin & imax) + ((imin ^ imax) >> 1);
 9             j = half - i;
10             if (i > 0 && j < n && nums1[i - 1] > nums2[j]) imax = i - 1;
11             else if (j > 0 && i < m && nums2[j - 1] > nums1[i]) imin = i + 1;
12             else break;
13         }
14         int num1;
15         if (!i) num1 = nums2[j - 1];
16         else if (!j) num1 = nums1[i - 1];
17         else num1 = max(nums1[i - 1], nums2[j - 1]);
18         if ((m + n) & 1) return num1;
19         int num2;
20         if (i == m) num2 = nums2[j];
21         else if (j == n) num2 = nums1[i];
22         else num2 = min(nums1[i], nums2[j]);
23         return (num1 + num2) / 2.0;
24     }
25 };

 

posted @ 2015-07-03 23:20  jianchao-li  阅读(209)  评论(0编辑  收藏  举报