繁体   English   中英

最大元素java的最小索引?

[英]Smallest index of the largest element java?

所以我编写了代码来给我一个数组的最小元素的最小索引,这意味着如果我的数组中有双精度数,它会给我一个具有最小索引的元素,例如:

myList = {1,3,1,4,5,5}; 运行代码时,它会给我 0 而不是 2 的索引

我遇到的问题是将此代码转换为二维数组?

我的代码:

public static int indexSmall(int[] array)
{
    int index = 0;
    int low = array[index];
    for(int i = 0; i < array.length; i++)
    {
        if (low > array[i])
        {
            low = array[i];
            index = i;
        }
    }

    return index;
}

基本上相同的事情,但您将不得不利用两个变量来跟踪行和列索引,因为它不再是您要查找的二维数组中的一个索引。 在这一点上,您想要返回什么完全取决于您。

public static int indexSmall(int[] array)
{
    int row = 0;
    int col = 0;
    int low = array[row][col];
    for(int i = 0; i < array.length; i++) //array.length is the number of 
                                          //arrays in the 2D array aka the number of rows
    {
        for(int j = 0; j < array[i].length; j++) //array[i].length is the number of elements
                                                 //in one of the arrays in the 2D arrays aka 
                                                 //the number of columns
            {
            if (low > array[i][j])
            {
                low = array[i][j];
                row = i;
                col = j
            }
        }
    }

    return row; //you can also return col or a combination of the two
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM