给你一个满足下述两条属性的m x n
整数矩阵:
target
,如果target
在矩阵中,返回true
;否则,返回false
。示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
算法思路:
matrix[row][n] < target
则对比下一行末的元素class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = 0, n = matrix[0].length - 1, m = matrix.length;
while(row < m && matrix[row][n] < target){
row++;
}
if(row >= m){
return false;
}
// 遍历
for(int num : matrix[row]){
if(num == target){
return true;
}
}
return false;
}
}
算法思路:
m * n - 1
的升序一维数组进行二分查找二分查找算法是用分治策略实现对n个元素进行排序的算法。详细可见 分治法的基本思想与例子解析
class Solution {
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) {
low = mid + 1;
} else if (x > target) {
high = mid - 1;
} else {
return true;
}
}
return false;
}
}