编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 输出:true
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 输出:false
思路:根据题目特点不难发现若将该矩阵中的元素看成一个一维数组即为一个有序(升序)的“一维数组”,而该题目又是一个“查找指定元素”的题目,所以可以尝试用“二分查找法”来实现,所以现在的难点就是如何将二维数组和一维数组互换的操作。
示例:
1 | 3 | 5 | 7 |
10 | 11 | 16 | 20 |
23 | 30 | 34 | 60 |
以其中的“3”为target,其在二维数组中的坐标为(0,1),若将该二维数组看成一维数组,则“3”的索引为“1”所以二维化一维度的公式为:”x * col(二维数组总的列数) + y “ (其中x,y为二维数组中target的横纵坐标),所以倒过来不难发现一维化二维数组的公式可以为:”(index / col, index % col) (其中index为target在一维数组中的索引)。
再利用二分查找不难得到如下代码:
public class Leetcode74 {
}
class solution74 {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return false;
}
int row = matrix.length;
int col = matrix[0].length;
int left = 0;
int right =matrix[0].length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; //防止超出int类型数的范围
int element = matrix[mid/col][mid%col];
if (element == target) {
return true;
} else if (element > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return false;
}
}