, , - (.. ), , O (n * m). .
, Binary Search O (lg n). . , , , . , , 1 . Python:
import math
def binSearch(value, data):
bottom = 0
top = len(data) -1
while bottom <= top:
i = int(bottom + math.floor((top - bottom)/2))
if data[i] == value:
return i
elif data[i] > value:
top = i - 1
else:
bottom = i + 1
return None
, . , , n x m mat, , i, mat[i][0] , mat[i][n] . , j, mat[0][j] fo , mat[m][j] . , mat[i][0] <= value <= mat[i][n] , i. , mat[0][j] <= value <= mat[m][j] , j.
, , , , .
for row in mat:
if (row[0] <= value) AND (row[len(row) - 1] >= value): #if the value could possibly be in the row
result = binSearch(value, row)
if result: #if we found it
return result
binSearch() - O (lg m). binSearch() , , O (n * lg m).
O (lg n * lg m), . , . .