作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/sou-suo-er-wei-ju-zhen-by-leetcode-solut-vxui/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
个人微改:
class matrix{
public boolean searchMatrix(int[][] matrix,int target) {
int m = matrix.length,n=matrix[0].length;
int low=0,high=m*n-1;
while(low<=high) {
int mid = (high-low)/2+low;
int x = matrix[mid/n][mid%n];
if(x>target) {
high=mid-1;
}else if(x<target) {
low=mid+1;
}else {
return true;
}
}
return false;
}
}
public class Search_A_2D_Matrix {
public static void main(String args[]) {
matrix hah = new matrix();
int[][] a = new int[][] {{1,3,5,7},{10,11,16,20},{23,30,34,60}};
System.out.println(hah.searchMatrix(a,3));
System.out.println(hah.searchMatrix(a,13));
}
}

本文介绍了一种高效的搜索算法,用于在一维表示的二维矩阵中查找目标值。该矩阵的特点是每一行从左到右单调递增,且每一行的第一个整数大于前一行的最后一个整数。通过将矩阵转化为一维数组并使用二分查找,可以在O(log n)的时间复杂度内完成搜索。

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



