首页 > 代码库 > Median of Two Sorted Arrays -- leetcode
Median of Two Sorted Arrays -- leetcode
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)).
下列算法的时间复杂度为O(log (k)), k = min(m,n)。比题目要求的还要好一些。
class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int *sa = m <= n ? A : B; int *la = m <= n ? B : A; const int lens = m <= n ? m: n; const int lenl = m <= n ? n: m; const int c = (lens + lenl -1) / 2; int ls = 0; int us = lens - 1; const bool odd = (m + n) % 2; double result = 0; if (!lens && lenl) result = odd ? la[c] : la[c] + la[c+1]; while (ls <= us) { const int cs = (us + ls) / 2; const int cl = c - cs; if (sa[cs] < la[cl]) { if (ls != cs) ls = cs; else if (cl == 0 || sa[cs] >= la[cl-1]) { result = sa[cs]; if (!odd) result += cs < (lens-1) ? min(sa[cs+1], la[cl]) : la[cl]; break; } else if (cs == us) { result = la[cl-1]; if (!odd) result += la[cl]; break; } else ls = cs + 1; } else if (sa[cs] > la[cl]) { if (us != cs) us = cs; else if (cs == ls || la[cl] >= sa[cs-1]) { result = la[cl]; if (!odd) result += cl < (lenl-1) ? min(sa[cs], la[cl+1]) : sa[cs]; break; } else us = cs - 1; } else { result = sa[cs]; if (!odd) result += la[cl]; break; } } return odd ? result : result / 2; } };
Median of Two Sorted Arrays -- leetcode
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。