Hello Java.
第74题:
题目描述:
编写一个高效的算法来判断m x n矩阵中,是否存在一个目标值。该矩阵具有如下特性:
1.每行中的整数从左到右按升序排列。
2.每行的第一个整数大于前一行的最后一个整数。
示例:
输入:matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
输出:true
输入:matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
输出:false
题目链接:
https://leetcode-cn.com/problems/search-a-2d-matrix/
代码:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
/* 入参判断 */
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int head = 0;
int tail = matrix[0].length - 1;
for (int i = 0; i < matrix.length; i++) {
/* 最小的还比目标值大 */
if (matrix[i][head] > target) return false;
/* 没有或不在这一行里 */
else if (matrix[i][tail] < target) continue;
/* 找到范围行开始遍历 */
else {
for (int j = head; j < matrix[0].length; j++) {
if (matrix[i][j] == target) return true;
}
return false;
}
}
return false;
}
}
二分查找代码:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int row = matrix.length;
int col = matrix[0].length;
int sta = 0;
int end = row * col - 1;
/* 将二维数组视作一位数组进行二分查找 */
while (sta != end) {
int mid = (sta + end - 1) / 2;
if (matrix[mid / col][mid % col] < target) sta = mid + 1;
else end = mid;
}
return matrix[end / col][end % col] == target;
}
}
第240题:
题目描述:
编写一个高效的算法来判断m x n矩阵中,是否存在一个目标值。该矩阵具有如下特性:
1.每行的元素从左到右升序排列。
2.每列的元素从上到下升序排列。
示例:
输入:matrix = [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
输出:当target = 5时返回true;当target = 20时返回false
题目链接:
https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
二分查找代码:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
/* 入参判断 */
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
/* 从右上角开始 */
int x = 0;
int y = matrix[0].length - 1;
while (x < matrix.length && y >= 0) {
/* 右上角值小于目标值-去掉一行 */
if (matrix[x][y] < target) x++;
/* 右上角值大于目标值-去掉一列 */
else if (matrix[x][y] > target) y--;
else return true;
}
return false;
}
}
杨氏矩阵
- 杨氏矩阵是典型的一种题号240中的矩阵,解法也非常经典
- 在74题中的矩阵是一个杨氏矩阵的类似体,化用二分查找的思想就可以了
- 参考资料:杨氏矩阵
待续ヾ(=・ω・=)o