Given a 2D matrix that contains integers only, which each row is sorted in an ascending order. The first element of next row is larger than (or equal to) the last element of previous row.
Given a target number, returning the position that the target locates within the matrix. If the target number does not exist in the matrix, return {-1, -1}.
Assumptions:
- The given matrix is not null, and has size of N * M, where N >= 0 and M >= 0.
Examples:
matrix = { {1, 2, 3}, {4, 5, 7}, {8, 9, 10} }
target = 7, return {1, 2}
target = 6, retu
def search(self, matrix, target):
"""
input: int[][] matrix, int target
return: int[]
"""
#index = row * 3 + column
#row = index%3, column = index//3
if not matrix or not matrix[0]:
return [-1,-1]
N=len(matrix)
M=len(matrix[0])
left = 0
right = N*M-1
while left < right: #相等的时候不进循环
mid=(left+right)//2
row = mid // M
column = mid % M
if matrix[row][column] > target:
right = mid - 1
elif matrix[row][column] < target:
left = mid + 1
else:
return [row,column]
#left和right相等了
row = left // M
column = left % M
if matrix[row][column] == target:
return [row,column]
else:
return [-1,-1]
rn {-1, -1} to represent the target number does not exist in the matrix.