java 如何从二维数组中找到索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7535556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:23:04  来源:igfitidea点击:

How to find a index from a two dimensional array

java

提问by MNX1024

What I'm trying to do is print the largest number within a two dimensional array and it's index location. I'm able to find the largest number, but I can't seem to figure out how to print it's index location. Anyway, here's what I have so far:

我想要做的是打印二维数组中的最大数字及其索引位置。我能够找到最大的数字,但我似乎无法弄清楚如何打印它的索引位置。无论如何,这是我到目前为止所拥有的:

public static void main(String[] args) {
    int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};

    double max = arr[0][0];
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr.length; j++) {
            if (arr[i][j] > max) {
                max = arr[i][j];

            }
        }
    }
    System.out.println(max);
    System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of 

回答by cwallenpoole

Right now, you should consistently get 2 * arr.length as the final value. That isn't what you are probably looking for. It looks like you want to know the coordinates for the max value. To do this, you'll need to cache the values of the indexes and then use them later:

现在,您应该始终获得 2 * arr.length 作为最终值。这可能不是你要找的。看起来您想知道最大值的坐标。为此,您需要缓存索引的值,然后稍后使用它们:

public static void main(String[] args) {
    int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
    int tmpI = 0;
    int tmpJ = 0;
    double max = arr[0][0];
    // there are some changes here. in addition to the caching
    for (int i = 0; i < arr.length; i++) {
        int[] inner = arr[i];
        // caches inner variable so that it does not have to be looked up
        // as often, and it also tests based on the inner loop's length in
        // case the inner loop has a different length from the outer loop.
        for (int j = 0; j < inner.length; j++) {
            if (inner[j] > max) {
                max = inner[j];
                // store the coordinates of max
                tmpI = i; tmpJ = j;
            }
        }
    }
    System.out.println(max);
    // convert to string before outputting:
    System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")");

回答by Costis Aivalis

Be careful with your array dimensions! The second for-statement most of you have is wrong. It should go to up to arr[i].length:

小心你的数组维度!大多数人的第二个 for 语句是错误的。它应该达到 arr[i].length

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        if (arr[i][j] > max) {
            max = arr[i][j];
            tmpI = i; tmpJ = j;
        }
    }
}

回答by Bhesh Gurung

int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};

int max = arr[0][0];
int maxI = 0, maxJ = 0;

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr.length; j++) {
        if (arr[i][j] > max) {
            max = arr[i][j];
            maxI = i;
            maxJ = j;
        }
    }
}
System.out.println(max);
System.out.println(maxI + "," + maxJ); 

回答by J V Jeoffer

//C++ code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> b;
vector<int> c;
int Func(int a[][10],int n)
{
    int max;
    max=a[0][0];
    for(int i=0;i<n;i++)
    {
            for(int j=0;j<n;j++)
            {
                    if(a[i][j]>max)
                    {
                                   max=a[i][j];
                                   b.push_back(i);
                                   c.push_back(j);
                                   }

                    }
                    }
                    b.push_back(0);
                    c.push_back(0);
                    return max;
                    }
    void display(int a[][10],int n)
    {
         for(int i=0;i<n;i++)
    {
            for(int j=0;j<n;j++)
            {
                    cout<<a[i][j]<<"\t";
                    }
                    cout<<endl;
                    }
                    }

int main()
{
    int a[10][10],n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
            for(int j=0;j<n;j++)
            {
                    cin>>a[i][j];
                    }
                    }
                    cout<<endl;
                    display(a,n);
                    cout<<endl;
                    cout<<Func(a,n)<<" is the greatest "<<endl;
                    if(b.size()==1&&c.size()==1)
                    {
                                            cout<<"Location is (1,1)"<<endl;
                                            }
                                            else
                                            {
                                                 b.erase(b.end() - 1);
                                                 c.erase(c.end() - 1);
                    cout<<"Location is "<<"("<<b.back()+1<<","<<c.back()+1<<")"<<endl;
                    }
                    return 0;
                    }

回答by J V Jeoffer

You're just adding the indices i and j together and then printing it to the screen. Since you're running throug the entire loop it's just going to be equal to 2*arr.length-2. What you need to do is store the values of i and j when you encounter a new max value.

您只需将索引 i 和 j 相加,然后将其打印到屏幕上。由于您正在运行整个循环,因此它将等于 2*arr.length-2。您需要做的是在遇到新的最大值时存储 i 和 j 的值。

For example:

例如:

int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};

int max = arr[0][0]; //dunno why you made it double when you're dealing with integers
int max_row=0;
int max_column=0;
for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr.length; j++) {
        if (arr[i][j] > max) {
            max = arr[i][j];
            max_row=i;
            max_column=j;

        }
    }
System.out.println("The max is: "+max+" at index ["+max_row+"]["+max_column+"]");

回答by Michael Aaron Safyan

Store i, j whenever you update max.

每次更新 max 时存储 i, j。

回答by RichW

You've got a two-dimensional array, therefore you need to know both indexes. Adding them together won't do because you lose which-is-which. How about this:

您有一个二维数组,因此您需要知道两个索引。将它们加在一起是行不通的,因为你失去了哪个是哪个。这个怎么样:

System.out.println("[" + i + "][" + j + "]");

回答by Joe

This would be if you wanted a single index into a flatten array:

如果您想要一个扁平数组的单个索引,那就是:

public static void main (String[] args) throws java.lang.Exception
{
        int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
            int[] flattened = new int[6*3]; // based off above
            int maxIndex = 0;
            double max = arr[0][0];
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < arr.length; j++) {
                    flattened[i + j] = arr[i][j];
                    if (arr[i][j] > max) {
                        max = arr[i][j];
                        maxIndex  = i+j;
                    }
                }
        }
    System.out.println(max);
    System.out.println(flattened [maxIndex]);
}

回答by abdolence

Don't sure that you implement effective algorithm, but why you just don't save indices i,j in another variables when you set max. This is very simple.

不确定您是否实现了有效的算法,但是为什么在设置 max 时不将索引 i,j 保存在另一个变量中。这很简单。

if (arr[i][j] > max) {
    max = arr[i][j];
    maxX = i;
    maxY = j;
}

FYI If you want look at "insertion sorting" algorithms if you want better implementation.

仅供参考,如果您想要更好的实现,则想查看“插入排序”算法。