74.搜索二维矩阵
解题思路:
package leadcode;
/**
* @author : icehill
* @description : 搜索二维矩阵
* 编写一个高效的算法来判断m x n矩阵中,是否存在一个目标值。该矩阵具有如下特性:
* 每行中的整数从左到右按升序排列。
* 每行的第一个整数大于前一行的最后一个整数。
* 示例 1:
* 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
* 输出:true
* 示例 2:
* 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
* 输出:false
* 提示:
* m == matrix.length
* n == matrix[i].length
* 1 <= m, n <= 100
* -10^4 <= matrix[i][j], target <= 10^4
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/search-a-2d-matrix
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* 解题思路:可以把二维矩阵看成是多个有序序列,可以先通过行的二分查找搜索,搜索目标值所在行,
* 再对某一行进行二分查找
* 时间复杂度:O(logmm)=O(logm)+O(logn) 空间复杂度:O(1)
* @date : 2021-05-21
*/
public class Solution74 {
public static void main(String[] args) {
int[][] matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
Solution74 solution74 = new Solution74();
System.out.println(solution74.searchMatrix(matrix, 3));
System.out.println(solution74.searchMatrix(matrix, 0));
}
public boolean searchMatrix(int[][] matrix, int target) {
//先找行,再找列,分别进行二分查找
int row = matrix.length - 1;
int column = matrix[0].length - 1;
int rowLeft = 0;
int rowRight = row;
while (rowLeft <= rowRight) {
int mid = (rowLeft + rowRight) / 2;
//如果没有对应行,直接返回false
if (target < matrix[rowLeft][0] || target > matrix[rowRight][column]) {
return false;
}
if (matrix[rowLeft][0] <= target && target < matrix[mid][0]) {
rowRight = mid - 1;
} else if (matrix[mid][0] <= target && target <= matrix[mid][column]) {
rowLeft = mid;
break;
} else {
rowLeft = mid + 1;
}
}
int columnLeft = 0;
int columnRight = column;
int r = rowLeft;
while (columnLeft <= columnRight) {
int mid = (columnLeft + columnRight) / 2;
if (matrix[r][mid] == target) {
return true;
} else if (matrix[r][mid] > target) {
columnRight = mid - 1;
} else {
columnLeft = mid + 1;
}
}
return false;
}
}