NOTE
Search a 2D Matrix
Search a matrix whose rows and columns are both sorted, starting from the top-right corner.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Write an efficient algorithm to search for a target value target in an m x n matrix. The matrix has the following properties:
The elements in each row are sorted in ascending order from left to right. The elements in each column are sorted in ascending order from top to bottom.
2. Approach
- Approach 1
- Start from the top-right corner and search toward the bottom-left
- Approach 2
- Use binary search on each row
3. Implementation
func searchMatrix(matrix [][]int, target int) bool {
row := 0
col := len(matrix[0])-1
for row < len(matrix) && col >= 0 {
if matrix[row][col] < target {
row++
}else if matrix[row][col] > target {
col--
}else {
return true
}
}
return false
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub