如何获取2D数组中元素的索引?

时间:2017-02-21 18:54:32

标签: java multidimensional-array

int[][] triangle = {  
                              {75},
                             {87,64}, //If index is 0, then start from j = 0 in 3rd row (24, 56, 88)
                               {24, 56, 88}, // if index is 2 then start from j = 2 in 4th row (43, 45, 67, 76),  and compare 67 and 76, and find the max
                               {43, 45, 67, 76}
  };

  for (int i = 0; i < array.length - 1; i++) {
   for (int j = 0; j < array[i].length; j++) {
        int  x = triangle[i][j];
         int y = triangle[i][j + 1];
            int max = Math.max(x, y);
      if (someCondition) {
          //getTheIndexOFMaxVariable (Here If I am looking for 64 then it should give me 1 as an index)
       }
    }
 }
  • 我的问题是,如果我正在寻找元素64,那么它应该将索引作为1代替[1][1]

有什么方法可以获得像1而不是[1][1]这样的数组的索引。

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

通过将2D数组int[][]转换为List<List<Integer>>,您可以利用indexOf查找max的索引:

List<List<Integer>> triangle = new ArrayList<List<Integer>>();
    triangle.add(Arrays.asList(75));
    triangle.add(Arrays.asList(95, 64));

    for (List<Integer> row : triangle) {
        // you can also ask for row.indexOf(max);
        System.out.println("At row: " + triangle.indexOf(row) + " is: " + row.indexOf(64));         
    }

答案 1 :(得分:1)

我可能会弄错,但索引不是j变量吗?

由于您使用第一个循环遍历数组,i将包含当前数组的索引(相对于父数组)。

但是第二个循环遍历子数组,因此元素的索引将是j

int[][] triangle = {  
            {75},
            {95,64}
  };

for (int i = 0; i < array.length - 1; i++) {
   for (int j = 0; j < array[i].length; j++) {
      // notice we use j variable to access the item, since it contains the index for current
      int item = array[i][j];

      if (item == 64) {
          // your code
       }
    }
 }

修改

根据更新,我建议扔掉Math.max函数,因为这会让你失去索引的轨迹。由于您只有2个要比较的元素,因此可以使用简单的if语句。

int x = triangle[i][j];
int y = triangle[i][j + 1];
int max = 0;
int indexOfMax = 0;

// using >= just in case if both numbers are equal
if (x >= y) {
    max = x;
    indexOfMax = j;
} else {
    max = y;
    indexOfMax = j + 1;
}

if (someCondition) {
    // your code
}