簡體   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