首页 > 其他 > 详细

[LeetCode] Median of Two Sorted Arrays

时间:2015-07-04 00:39:05      阅读:256      评论:0      收藏:0      [点我收藏+]

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, num1, num2;
 7         while (iMin <= iMax) {
 8             i = (iMin + iMax) / 2;
 9             j = half - i;
10             if (j > 0 && i < m && nums2[j - 1] > nums1[i])
11                 iMin = i + 1;
12             else if (i > 0 && j < n && nums1[i - 1] > nums2[j])
13                 iMax = i - 1;
14             else {
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                 break;
19             }
20         }
21         if ((m + n) & 1) return num1;
22         if (i == m) num2 = nums2[j];
23         else if (j == n) num2 = nums1[i];
24         else num2 = min(nums1[i], nums2[j]);
25         return (num1 + num2) / 2.0;
26     }
27 };

 

[LeetCode] Median of Two Sorted Arrays

原文:http://www.cnblogs.com/jcliBlogger/p/4619941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!