找不到。在包含O(n)中所有不同元素的nxn数组中

时间:2012-07-12 10:09:48

标签: algorithm

给出一个nxn元素数组,使每行按升序排列,每列按升序排列,设计一个O(n)算法来确定数组中是否有给定的元素x。您可以假设nxn数组中的所有元素都是不同的。

如果有人知道这个问题的解决方案,请告诉我。

1 个答案:

答案 0 :(得分:0)

从第1行开始,即最后一列,即i = 0,j = n-1

while true {
if (j< 0 || i > (n-1) )
 break; // element not found
if (array[i][j] == x)
 return i,j
else if (x < array[i][j])
 j = j -1; // and repeat
else 
 i = i+1; // and repeat
}

这是O(n)。说明:

从第一行和最后一列开始。 i = 0; j = n-1每次x小于currElement递减j否则递增i。

相关问题