-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_sorted_matrix.py
More file actions
30 lines (26 loc) · 1.01 KB
/
search_sorted_matrix.py
File metadata and controls
30 lines (26 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# You are given a two-dimensional array (matrix) of distinct integers where each row is sorted
# and each column is also sorted. The matrix does not necessarily have the same height and width.
# You are also given a target number, and you must write a function that returns
# an array of the row and column indices of the target number if it is contained in the matrix and [-1, -1]
# if it is not contained in the matrix.
def searchInSortedMatrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return [row, col]
return [-1, -1]
if __name__ == '__main__':
matrix = [
[1, 4, 7, 12, 15, 1000],
[2, 5, 19, 31, 32, 1001],
[3, 8, 24, 33, 35, 1002],
[40, 41, 42, 44, 45, 1003],
[99, 100, 103, 106, 128, 1004],
]
target = 44
assert searchInSortedMatrix(matrix, target) == [3, 3]