Complete the code to check if the matrix is empty.
if len(matrix) == [1] { return false }
We check if the number of rows is zero to know if the matrix is empty.
Complete the code to get the number of columns in the matrix.
cols := len(matrix[1])
We use matrix[0] to access the first row and get its length for columns.
Fix the error in the binary search condition to find the target in a row.
for left <= right { mid := left + (right - left) / 2 if matrix[row][mid] == [1] { return true } else if matrix[row][mid] < target { left = mid + 1 } else { right = mid - 1 } }
The condition must compare the matrix element with the target value.
Fill both blanks to correctly perform binary search on the matrix rows.
for left, right := 0, [1] - 1; left <= right; { mid := left + (right - left) / 2 if matrix[mid][0] == target { return true } else if matrix[mid][0] < [2] { left = mid + 1 } else { right = mid - 1 } }
We set right to last row index (len(matrix)-1) and compare matrix[mid][0] with target.
Fill all three blanks to complete the function that searches target in the 2D matrix.
func searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 || len(matrix[1]) == 0 {
return false
}
rows, cols := len(matrix), len(matrix[0])
left, right := 0, rows - 1
for left <= right {
mid := left + (right - left) / 2
if matrix[mid][0] == [2] {
return true
} else if matrix[mid][0] < target {
left = mid + 1
} else {
right = mid - 1
}
}
row := right
if row < 0 {
return false
}
left, right = 0, cols - 1
for left <= right {
mid := left + (right - left) / 2
if matrix[row][mid] == target {
return true
} else if matrix[row][mid] < [3] {
left = mid + 1
} else {
right = mid - 1
}
}
return false
}Check if first row exists with matrix[0], compare matrix[mid][0] with target, and compare matrix[row][mid] with target.