如果我们有一个排序array
:
12 13 14 17
17 19 21 28
21 56 68 190
67 87 92 900
我们有密钥21
和62
。我们必须确定array
中是否存在这些密钥。使用2个循环很容易使用n^2
(n-square)顺序。但是如何使用订单n
执行此操作。
答案 0 :(得分:0)
可以做到......但效率不高:
for(int i = 0 ; i < array2d.length * array2d[0].length ; i++) {
// i % array2d.length is the row
// i / array2d.length is the col
if (array2d[i % array2d.length][i / array2d.length] == // your condition
}
答案 1 :(得分:0)
您可以使用binary search轻松实现O(log(n))
。假设您拥有数组 a[1..N][1..N]
,并且想要搜索 row
和 col
值 R
。伪代码是:
lower_row <- 0
upper_row <- N
while (lower_row < upper_row):
mid_row <- (lower_row + upper_row) / 2
if (R >= a[mid_row+1][1])
lower_row = mid_row+1
else if (R <= a[mid_row][N])
upper_row = mid_row
# now lower_row = upper_row = row
row <- lower_row
left_col <- 0
right_col <- N
while (left_col < right_col):
mid_col <- (left_col + right_col) / 2
if (R > a[row][mid_col])
left_col = mid_col+1
else if (R <= a[row][mid_col]
right_col = mid_col
# now left_col = right_col = col
col <- left_col
return row, col
现在 row
和 col
是数组中值的坐标。
<强>更新强>
看起来你只需要使用复杂性O(N)
来完成它,所以它非常简单。伪代码:
row <- 1;
for i from 1 to N:
if (a[i][1] < R and R < a[i][N])
row = i
for j from 1 to N:
if (a[row][j] = R)
col = j
return row, col
答案 2 :(得分:0)
我相信你的阵列的每一行和每一列都是有序的 考虑第一行中的最后一个元素。
Row = 0
Col = N - 1
if Value = A[Row, Col] then
element is found
else
if Value < A[Row, Col] then Value cannot be in this column, and we have to move left
Col = Col - 1
else
if Value > A[Row, Col] then Value cannot be in this row, and we have to move down
Row = Row + 1
Repeat steps until Value is found or border is reached.
我们总是只向左和向下移动,因此复杂度最多为(N + N)步= O(N)