leetcode median of two sorted arrays
2014-07-28 20:13
447 查看
找两个排好序的数组的中位数。
用快排的想法去找,发现code真不容易,写成一团了。
收藏两个别人的代码吧。。
用快排的想法去找,发现code真不容易,写成一团了。
收藏两个别人的代码吧。。
double findMedianSortedArrays2(int A[], int m, int B[], int n) { if (m > n) return findMedianSortedArrays(B, n, A, m); int minidx = 0, maxidx = m, i, j, num1, mid = (m + n + 1) >> 1, num2; while (minidx <= maxidx)//实际上是找到A和B一起的前mid个数,i+j=mid,从而A[0]到[i-1]和B[0]到[j-1]一共就是mid个数 { i = (minidx + maxidx) >> 1; j = mid - i; if (i<m && j>0 && B[j - 1] > A[i]) minidx = i + 1; else if (i>0 && j<n && B[j] < A[i - 1]) maxidx = i - 1; else { if (i == 0) num1 = B[j - 1]; else if (j == 0) num1 = A[i - 1]; else num1 = max(A[i - 1], B[j - 1]); break; } } if (((m + n) & 1)) return num1; if (i == m) num2 = B[j]; else if (j == n) num2 = A[i]; else num2 = min(A[i], B[j]); return (num1 + num2) / 2.; } int getkth(int s[], int m, int l[], int n, int k){ // let m <= n if (m > n) return getkth(l, n, s, m, k); if (m == 0) return l[k - 1]; if (k == 1) return min(s[0], l[0]); int i = min(m, k / 2), j = min(n, k / 2); if (s[i - 1] > l[j - 1]) return getkth(s, m, l + j, n - j, k - j); else return getkth(s + i, m - i, l, n, k - i); return 0; }
相关文章推荐
- leetcode Median of Two Sorted Arrays
- [leetcode]Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- LeetCode: Median of Two Sorted Arrays
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays 解题报告
- LeetCode: Median of Two Sorted Arrays
- LeetCode刷题笔录 Median Of Two Sorted Arrays
- LeetCode Online Judge 题目C# 练习 - Median of Two Sorted Arrays
- leetCode_Median of Two Sorted Arrays
- LeetCode: Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- Median of Two Sorted Arrays-----LeetCode
- [LeetCode题解004]Median of Two Sorted Arrays
- LeetCode —— Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays