码迷,mamicode.com
首页 > 其他好文 > 详细

4. Median of Two Sorted Arrays

时间:2016-08-09 20:23:36      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
 4         int len = nums1.size() + nums2.size();
 5         int i = 0, j = 0; // 下标
 6         int count = 0; // 计数
 7         int curr = 0; // 当前数值
 8         int median = 0; // 返回值
 9         while (i < nums1.size() && j < nums2.size()) {
10             if (nums1[i] < nums2[j]) {
11                 curr = nums1[i]; ++ i; 
12             }
13             else {
14                 curr = nums2[j]; ++ j; 
15             }
16             ++ count;
17             if (len % 2 && count == len / 2 + 1) {
18                 median += curr; break;
19             }
20             if (len % 2 == 0 && (count == len / 2 || count == len / 2 + 1)) {
21                 median += curr;
22                 if (count == len / 2 + 1) break;
23             }
24         }
25         if (i != nums1.size()) {
26             while (count < len / 2 + 1) {
27                 curr = nums1[i ++]; ++ count;
28                 if (len % 2 && count == len / 2 + 1) median += curr;
29                 if (len % 2 == 0 && (count == len / 2 || count == len / 2 + 1)) median += curr;
30             }
31         } else {
32             while (count < len / 2 + 1) {
33                 curr = nums2[j ++]; ++ count;
34                 if (len % 2 && count == len / 2 + 1) median += curr;
35                 if (len % 2 == 0 && (count == len / 2 || count == len / 2 + 1)) median += curr;
36             }
37         }
38         double res = static_cast<double>(median);
39         if (len % 2 == 0) res /= 2;
40         return res;
41     }
42 };

 

4. Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/shadowwalker9/p/5754423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!