So first thing. Since you are trying to find a number that is MAX at row and MIN at column, it means you are trying to find multiple numbers. As such, there should be some resetting code for resetting the max and min in order to find new max and min.
Then, what you need to think about is HOW you are gonna find it. Since it must be max in the column first, you have to iterate all positions in each row first while recording the max position. Then you iterate that particular column associated with the max position in that row. You get it? You ONLY iterate the column again (beside the first time) when you finish an entire row first and know the position.
@Alex Rudenko notes that since there are negative numbers in the matrix, an initial value of max and min should default to
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
which is essential for the below code to work.
So the code for the last block should look something like this:
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[0].length; j++){
if (matrix[i][j] > max){
max = matrix[i][j];
maxPos = j; //declare this beforehand
}
}
for (int a = 0; a < matrix.length; a++ ){
if( matrix[a][maxPos] < min){
min = matrix[a][maxPos];
}
}
if(max == min) {
System.out.println(matrix[i][maxPos]);
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
}
}
That’s it! There could be something down to avoid repetition on already checked position, but this is the central logic of this operation.
Also, I assume you are only printing the max&min number. You can also save those numbers in an array or something if you need to use it later.
Since you are trying to learn, I would suggest refrain from using advanced methods. This is a helpful basic to solidify you coding muscle.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…