一:解题思路
这个题目是二分搜索的一个变形题目。这个题目的解题关键在于将二维数组看做成一维数组,然后利用二分的思想不断的进行更新。matrix[r][c],r=mid/n,c=mid%n。其中n为数组的列数。Time:O(log(m*n)),Space:O(1)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.size() == 0 || matrix[0].size() == 0) return false; int m = matrix.size(); int n = matrix[0].size(); int low = 0, high = m * n - 1; while (low <= high) { int mid = low + (high - low) / 2; int r = mid / n; int c = mid % n; if (matrix[r][c] < target) low = mid + 1; else if (matrix[r][c] > target) high = mid - 1; else return true; } return false; } };
Java:
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null || matrix.length==0) return false; if(matrix[0]==null || matrix[0].length==0) return false; int m=matrix.length; int n=matrix[0].length; int low=0,high=m*n-1; while(low<=high) { int mid=low+(high-low)/2; int r=mid/n; int c=mid%n; if(matrix[r][c]<target) low=mid+1; else if(matrix[r][c]>target) high=mid-1; else return true; } return false; } }
来源:https://www.cnblogs.com/repinkply/p/12643190.html