在Java中搜索二维数组可以使用循环遍历或者二分查找算法来实现。下面是两种方法的示例代码:
public class SearchIn2DArray {
public static boolean search(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int row = 0;
int col = cols - 1;
while (row < rows && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] < target) {
row++;
} else {
col--;
}
}
return false;
}
public static void main(String[] args) {
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 target = 5;
boolean result = search(matrix, target);
System.out.println("Result: " + result);
}
}
public class SearchIn2DArray {
public static boolean search(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0;
int right = rows * cols - 1;
while (left <= right) {
int mid = (left + right) / 2;
int midValue = matrix[mid / cols][mid % cols];
if (midValue == target) {
return true;
} else if (midValue < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 60}
};
int target = 3;
boolean result = search(matrix, target);
System.out.println("Result: " + result);
}
}
以上代码示例中,第一个方法是通过循环遍历二维数组来搜索目标值,时间复杂度为O(m+n),其中m为行数,n为列数。第二个方法是利用二分查找算法在有序的二维数组中搜索目标值,时间复杂度为O(log(m*n)),其中m为行数,n为列数。
推荐的腾讯云相关产品:腾讯云云服务器(ECS)和腾讯云数据库(TencentDB)。
领取专属 10元无门槛券
手把手带您无忧上云