 # How to create a Method that would return indices of an element in some 2D array in java.

I am trying to generate a function find_indices(int num) in java which when called with a certain parameter would check the presence of that parameter in a 2D array say K,and would return its indices (indices in the matrix K).

I am talking about something similar like this:

``````int min=(int)Math.min(K[i][j],K[j][i]);
find_indices(min);
//
find_indices(int num)
{
//Now this method will return the indices of num in the 2D array K(if present)
}
``````

Okay there are two things i have no idea about:

• When i call a function that is supposed to return me two variables(i & j),how do i catch/hold/store them when they are returned?
• I need an efficient way to search for num in the matrix K[][]. Since the number of testcases would be high,and on top of that if i use two for loops(O(n^2)searching technique) for each of such test cases, i guess i would run into a TLE. Hence i need to know the good ways to optimize searching process in a 2D array.

Any kind of help/suggestions regarding the above problems would be extremely helpful.
Thank you.

@codegagu : Regarding the return value , you can make a struct or class that has two integer fields and your return object can have those two fields set .

Regarding the efficiency of findIndices , how many times you need to find the min in same matrix , and does the matrix change in between and if yes how many entries are changed in one go ? You will have to spend initial n^2 time to find min entry but when updates happen you can always store the current min without doing n^2 operations .

Also if the initial matrix has some sort order or some property , you may not require the initial n^2 time also . You need to be more clear regarding your question .

@codegagu : Just noticed you have asked it for Java .

In C or C++ , you could have used “struct”

In Java you need to make an “inner class” .

So suppose you have class called “Main” in which you are solving your problem and it looks like this

public class Main {

public class Point {

int x ;

int y ;

public Point (int xx ,int yy) {

x = xx;

y = yy;

}

static Main main;

public static void main (String[] args) {

main = new Main();

// here you call findIndices

Point p = findIndices();

int x = p.x;

int y = p.y;

}

public static Point findIndices() {

int ansX ;

int ansY ;

// you find ansX and ansY through some logic .

// then you make an object and return .

return main.new Point(ansX,ansY);

}