从二维数组中找出对应数的下标,思路如下
遍历整个二维数组,当前数组下标值不是要查询的值的时候,就让col++,然后判断col是否大于等于二维数组的col值,如果是,那么说明需要判断下一行了,也就让col=0,row++。搞定!
public class TwoDimensionalArray {
public static void main(String[] args) {
int[][] arr = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
int num = 11;
int rows = 4;
int cols = 4;
Solution2 solution = new Solution2();
int[] index = solution.findNum(arr, num, rows, cols);
System.out.println("row=" + index[0] + "col=" + index[1]);
}
}
class Solution2 {
public int[] findNum(int[][] arr, int num, int rows, int cols) {
int[] index = new int[2];
int row = 0, col = 0;
boolean flag = false;
while (row < rows && col < cols) {
if (arr[row][col] == num) {
flag = true;
break;
} else {
col++;
if (col >= cols) {
row++;
col = 0;
}
}
}
if (flag) {
index[0] = row;
index[1] = col;
} else {
index[0] = -1;
index[1] = -1;
}
}
}