在Java中查找二维数组中的特定元素,你可以使用以下方法:
嵌套循环遍历
使用两个嵌套的for循环来遍历二维数组的每个元素。
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };int target = 5;boolean found = false;for (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++) {if (array[i][j] == target) {found = true;System.out.println("找到目标值 " + target + " 在位置 (" + i + ", " + j + ")");break;}}if (found) break;}if (!found) {System.out.println("未找到目标值 " + target);}

从左下角开始遍历
如果数组按行和列都是升序排列的,可以从左下角开始查找,这样可以减少遍历的次数。
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };int target = 5;boolean found = false;int row = array.length - 1;int col = 0;while (row >= 0 && col < array.length) {if (array[row][col] == target) {found = true;System.out.println("找到目标值 " + target + " 在位置 (" + row + ", " + col + ")");break;} else if (array[row][col] > target) {row--;} else {col++;}}if (!found) {System.out.println("未找到目标值 " + target);}
以上两种方法都可以用来在Java中查找二维数组中的特定元素。选择哪一种方法取决于你对数组结构的了解和性能上的考量
