NOTE
Search a 2D Matrix
Given a row- and column-sorted matrix and a target value, design an efficient algorithm to determine whether the value is present.
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
}
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub