求两个有序数组的median的平凡解法?# JobHunting - 待字闺中
K*k
1 楼
要求in place, 只要求O(m + n)的方法,不需要log(m + n)那个。我写的代码还是觉得太长,怎么简化才能在白板上写的下?
double GetMedian(int A[], int m, int B[], int n)
{
bool odd_length = ((m + n) % 2 == 0)? false : true;
int m1, m2;
int pos = (m + n + 1) / 2;
int count = 0;
int i = 0;
int j = 0;
while (i < m && j < n)
{
count++;
if (A[i] <= B[j])
{
if (count == pos)
{
m1 = A[i];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = A[i];
return (m1 + m2) / 2.0;
}
i++;
}
else
{
if (count == pos)
{
m1 = B[j];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = B[j];
return (m1 + m2) / 2.0;
}
j++;
}
}
while (i < m)
{
count++;
if (count == pos)
{
m1 = A[i];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = A[i];
return (m1 + m2) / 2.0;
}
i++;
}
while (j < n)
{
count++;
if (count == pos)
{
m1 = B[j];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = B[j];
return (m1 + m2) / 2.0;
}
j++;
}
return 0.0;
}
double GetMedian(int A[], int m, int B[], int n)
{
bool odd_length = ((m + n) % 2 == 0)? false : true;
int m1, m2;
int pos = (m + n + 1) / 2;
int count = 0;
int i = 0;
int j = 0;
while (i < m && j < n)
{
count++;
if (A[i] <= B[j])
{
if (count == pos)
{
m1 = A[i];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = A[i];
return (m1 + m2) / 2.0;
}
i++;
}
else
{
if (count == pos)
{
m1 = B[j];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = B[j];
return (m1 + m2) / 2.0;
}
j++;
}
}
while (i < m)
{
count++;
if (count == pos)
{
m1 = A[i];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = A[i];
return (m1 + m2) / 2.0;
}
i++;
}
while (j < n)
{
count++;
if (count == pos)
{
m1 = B[j];
if (odd_length)
return m1;
}
else if (count == pos + 1)
{
m2 = B[j];
return (m1 + m2) / 2.0;
}
j++;
}
return 0.0;
}