问题:
难度:medium
说明:
在二维数组里面判断是否存在一个元素。
题目连接:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
输入案例:
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
我的代码:
其实是对二维数组做一个二分法搜索即可,先搜索行,再搜索列,要注意搜索行的时候用该行的最小数和最大数作区间比较,然后再继续往下找对应的列。
Java:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0) return false;
int beginX = 0, endX = matrix.length - 1, midX = (beginX + endX) >> 1;
while(beginX < endX) {
int midMinV = matrix[midX][0];
int midMaxV = matrix[midX][matrix[0].length - 1];
if(midMaxV < target) beginX = midX + 1;
else if(midMinV > target) endX = midX - 1;
else break;
midX = (beginX + endX) >> 1;
}
int beginY = 0, endY = matrix[0].length - 1, midY = (beginY + endY) >> 1;
while(midX >= 0 && midX < matrix.length && beginY < endY) {
int midV = matrix[midX][midY];
if(midV < target) beginY = midY + 1;
else if(midV > target) endY = midY - 1;
else return true;
midY = (beginY + endY) >> 1;
}
return midX >= 0 && midY >= 0 && matrix[midX][midY] == target;
}
}