74. Search a 2D Matrix
Last updated
Last updated
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: trueInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: falsefunc searchMatrix(matrix [][]int, target int) bool {
rows, cols := len(matrix), len(matrix[0])
start, end := 0, rows*cols-1
for start+1 < end {
mid := start + (end-start)/2
if center := matrix[mid/cols][mid%cols]; center > target {
end = mid
} else if center < target {
start = mid
} else {
return true
}
}
if matrix[start/cols][start%cols] == target || matrix[end/cols][end%cols] == target {
return true
}
return false
}