https://oj.leetcode.com/problems/search-a-2d-matrix/
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
这一题你可以考虑二分,根据行和列分成四块。
但接下来只介绍一种比较简便的做法,我们一开始就把位置定在右上角,当当前数字比target大,往下走,当前数字比target小,就往左走。这样最后要不就是找到target返回true,要不就是过界返回false。这种做法的理念貌似是和dp有关的。。当然,我还不是特别明白。。也就是,我是背答案的。。谢谢。。囧
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0)
return false;
int right = matrix[0].length - 1;
int top = 0;
while(top < matrix.length && right >= 0){
if(target > matrix[top][right])
top++;
else if(target < matrix[top][right])
right--;
else
return true;
}
return false;
}
本文介绍了一种在二维矩阵中高效搜索目标值的方法,通过从右上角开始搜索,利用矩阵特性实现快速定位目标,避免全矩阵遍历,显著提升搜索效率。
129

被折叠的 条评论
为什么被折叠?



