【发布时间】:2011-09-29 23:47:45
【问题描述】:
问题: 给定一个矩阵,其中每一行和每一列都已排序,编写一个方法来查找其中的元素。
这是一个经典的面试问题,这是我的解决方案
boolean F(int[][] matrix, int hs, int he, int ws, int we)
{
if (hs > he || ws > we)
return false;
int m = (hs + he) / 2;
int n = (ws + we) / 2;
if (matrix[m][n] == t)
{
return true;
}
else if (matrix[m][n] < t)
{
// find the ele in the same row, right to [m][n]
F(m, m, n + 1, we);
// find the ele in the same col, upper to [m][n]
F(m + 1, he, n, n);
// find the ele in the area, where i>m,j>n
F(m + 1, he, n + 1, we);
}
else if (matrix[m][n] > t)
{
// very similar to previous part
}
}
算法的运行时间为log(m) + log(n)。我正在寻找一种更高效或代码更简洁的算法。
有更多的cmets,我想出了以下代码:
// return target recurrence in the matrix
int F(int[][] m, int rs, int re, int cs, int ce, int t){
int r1 = rs, r2 = re;
int c1 = cs, c2 = ce;
int r=0 , c = c1;
while( r1 < r2 && c1 < c2 ){
// find the last element that <= t in column c
r = FlastLess( r1, r2, c, t)
if( r == -1 ) break;
else{
// find the first ele in the row that is >=t
c = FfirstGreater( r, c1, c2, t);
if( c == -1) break;
else{
r2 = r;
c1 = c;
}// else
}// else
}// while
}// f
这里是函数 F1 和 F2 的链接 Find the first element in a sorted array that is greater than the target
void FlastLess(int s, int e, int t){
int l = s, h = e;
while( l != h ){
int mid = (l+h)/2;
if( mid >= t) high = mid - 1;
else {
if( high < t) low= mid + 1;
else low = mid;
}
}
void FfirstGreater(int s, int e, int t){
while(l < h){
mid = (l+h)/2;
if ( mid <= t) low = mid+1;
else high = mid;
}
}
}
【问题讨论】:
-
我可能是错的,但二进制搜索可能会尽可能快。
-
我不确定你的方法是否有效。想象一个矩阵,其第一行是 [0,10,20,..,90],下一行是 [1,11,21,..,91] 直到 [9,19,29,...,99 ]。在这种情况下,每一行和每一列都是有序的。现在你从 55 开始,你正在寻找 72。72 > 55 但它不在矩阵的下半部分。如果您正在寻找 19,它不在上半部分。可能我没看懂算法。我也不明白你如何有连续的“return”语句 - 这是无法访问的代码。
-
@secureFish 考虑新的答案。让我知道这是对的。
-
仅供参考:此数据结构也称为Young tableau。
标签: java arrays algorithm binary-search