1.Description
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
2.Example
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
3.Solution
1.找到target所在列,在遍历该列
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length-1;
int n = matrix[0].length-1;
for(int j=n;j>=0;j--) {
if(target>=matrix[0][j]&&target<=matrix[m][j]) {
for(int i=0;i<=m;i++) {
if(matrix[i][j]==target) {
return true;
}
}
}
}
return false;
}
}
2.两次二分查找
二分查找元素所在列,然后对该列二分查找
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rowIndex = binarySearchFirstColumn(matrix, target);
if (rowIndex < 0) {
return false;
}
return binarySearchRow(matrix[rowIndex], target);
}
public int binarySearchFirstColumn(int[][] matrix, int target) {
int low = -1, high = matrix.length - 1;
while (low < high) {
int mid = (high - low + 1) / 2 + low;
if (matrix[mid][0] <= target) {
low = mid;
} else {
high = mid - 1;
}
}
return low;
}
public boolean binarySearchRow(int[] row, int target) {
int low = 0, high = row.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (row[mid] == target) {
return true;
} else if (row[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
}
3.一次二分查找
将二维数组当成一位算,对数组下标进行二分查找
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int left = 0,right = m*n-1;
while(left<=right) {
int mid = (right-left)/2+left;
if(target>matrix[mid/n][mid%n]) {
left = mid+1;
}else if(target<matrix[mid/n][mid%n]) {
right = mid-1;
}else {
return true;
}
}
return false;
}
}