标签:pre tor eve 地址 tco media ati result blog
这道题感觉没什么讲的,需要注意的就是,num1,num2的长度并不相等,会有可能num2还没到尽头,num1就到尽头了
static double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) { auto length = nums1.size() + nums2.size(); int x = 0, y = 0, even = 0, i = 0; double results[2] = {0, 0}; double result = 0; if (length % 2 == 0) { length = (length / 2)+1; even = 1; } else length = (length + 1) / 2; while (length != 0 && x < nums1.size() && y < nums2.size()) { if(nums1[x]==nums2[y]){ results[i]=nums1[x]; ++x; } else if (nums1[x] > nums2[y]) { results[i] = nums2[y]; ++y; } else { results[i] = nums1[x]; ++x; } i = ++i % 2; --length; } if (length != 0) { if (x < nums1.size()) while (length != 0) { results[i] = nums1[x]; i = ++i % 2; ++x; --length; } else { while (length != 0) { results[i] = nums2[y]; i = ++i % 2; ++y; --length; } } } if (even) result = (results[0] + results[1]) / 2; else { result = results[0] > results[1] ? results[0] : results[1]; } return result; }
另在网上看到了一种优化算法,不过看了很久还是不怎么懂,地址在这里:
http://blog.csdn.net/linhuanmars/article/details/19905515
Leetcode--Median of Two Sorted Arrays
标签:pre tor eve 地址 tco media ati result blog
原文地址:http://www.cnblogs.com/INnoVationv2/p/6036827.html