标签:code 自己 二分 round hal 1.4 family double search
There are two sorted arrays nums1 and nums2 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)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
[2 3 5 7]
则
[2 3 / 5 7]
[2 3 4 5 6 7]
则
[2 3 (4/4) 5 6 7]
N Index of L / R
1 0 / 0
2 0 / 1
3 1 / 1
4 1 / 2
5 2 / 2
6 2 / 3
7 3 / 3
8 3 / 4
(L + R)/2 = (A[(N-1)/2] + A[N/2])/2
[6 9 13 18] -> [# 6 # 9 # 13 # 18 #] (N = 4) 偶数序列
position index 0 1 2 3 4 5 6 7 8 (N_Position = 9)
[6 9 11 13 18]-> [# 6 # 9 # 11 # 13 # 18 #] (N = 5) 奇数序列
position index 0 1 2 3 4 5 6 7 8 9 10 (N_Position = 11)
index ( L ) = ( N -1 ) / 2 = ( CutPosition - 1 ) / 2
index ( R ) = N / 2 = CutPosition / 2;
//CutPosition: 处理后序列的分割线位置
A1: [# 1 # 2 # 3 # 4 # 5 #] (N1 = 5, N1_positions = 11)
A2: [# 1 # 1 # 1 # 1 #] (N2 = 4, N2_positions = 9)
任意在 左半部分的数字 < 任意在 右半部分的数字
L1 = A1[(C1-1)/2]; R1 = A1[C1/2];
L2 = A2[(C2-1)/2]; R2 = A2[C2/2];
L1 <= R1 && L1 <= R2 && L2 <= R1 && L2 <= R2
L1 <= R2 && L2 <= R1
1. 如果有L1 > R2,则说明A1序列左半边有太多过大的数字,所以 我们需要将C1左移(或者C2右移)
2. 如果 L2 > R1,则说明A2序列左边有太多过大的数字,所以应该将C2左移(或者C1右移)
3. 如果都没有,那么说明该 分割线位置是正确的
4. 中位数medium就是 (max(L1,L2) + min(R1,R2)) / 2;
1. C1和C2可以互相决定,所以我们可以选择短一些的序列进行查找,从而使得算法时间复杂度为log(min(N1,N2))
2. 唯一的边界条件edge case是当分割线落在 0 和 2N 的位置上。比如:如果C2 = 2*N2,那么R2 = A2[ 2*N2 / 2] = A2[ N2 ],会越过边界。为了解决这个问题,我们可以这样处理:当 L 落到左边界,则令 L = INT_MIN, 当 R落到 右边界,则让R = INT_MAX
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int N1 = nums1.size();
int N2 = nums2.size();
// Make sure A2 is the shorter one.
if (N1 < N2) return findMedianSortedArrays(nums2, nums1);
- // If A2 is empty
if (N2 == 0) return ((double)nums1[(N1-1)/2] + (double)nums1[N1/2])/2;
int lo = 0, hi = N2 * 2;
while (lo <= hi) {
int mid2 = (lo + hi) / 2; // Try Cut 2
int mid1 = N1 + N2 - mid2; // Calculate Cut 1 accordingly
double L1 = (mid1 == 0) ? INT_MIN : nums1[(mid1-1)/2]; // Get L1, R1, L2, R2 respectively
double L2 = (mid2 == 0) ? INT_MIN : nums2[(mid2-1)/2];
double R1 = (mid1 == N1 * 2) ? INT_MAX : nums1[(mid1)/2];
double R2 = (mid2 == N2 * 2) ? INT_MAX : nums2[(mid2)/2];
if (L1 > R2) lo = mid2 + 1; // A1‘s lower half is too big; need to move C1 left (C2 right)
else if (L2 > R1) hi = mid2 - 1; // A2‘s lower half too big; need to move C2 left.
else return (max(L1,L2) + min(R1, R2)) / 2; // Otherwise, that‘s the right cut.
}
return -1;
}
4. Median of Two Sorted Arrays
标签:code 自己 二分 round hal 1.4 family double search
原文地址:http://www.cnblogs.com/zhxshseu/p/e8b7f500a1d2032fbdcf5ef587644af6.html