示例 1:
输入: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
public class Search2DMatrixII {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int m = matrix.length;
int n = matrix[0].length;
int row = 0, col = n - 1; // Start from the top-right corner从右上角开始
// {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}
while (row < m && col >= 0) {
if (matrix[row][col] == target) {
return true; // Found the target
} else if (matrix[row][col] > target) {
col--; // Move left in the current row 在当前行向左移动
} else {
row++; // Move down to the next row 向下移动到下一行
}
}
return false; // Target not found
}
public static void main(String[] args) {
Search2DMatrixII search = new Search2DMatrixII();
int[][] 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}
};
int target1 = 5;
int target2 = 20;
System.out.println("Target 5 found: " + search.searchMatrix(matrix, target1));
System.out.println("Target 20 found: " + search.searchMatrix(matrix, target2));
}
}