Example
Input : 5
2 3 1 7 3
4 1 9 6 8
5 5 2 4 4
6 5 2 6 7
8 4 2 2 2
Output : 4
My answer:
import java.util.Scanner;
class MatrixAnalyzer {
public static void main(String[] args) {
MatrixAnalyzer t = new MatrixAnalyzer();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int[][] a = new int[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
a[i][j] = kb.nextInt();
}
}
System.out.println(t.solution(n, a));
}
int solution(int n, int[][] a) {
int[][] b = new int[n][n];
for(int j = 0; j < n; j++) {
for(int i = 0; i < n; i++) {
int tmp = a[i][j];
int cnt = n - 1;
while(cnt >= 0) {
if(tmp == a[cnt][j]) {
b[i][j] += 1;
}
cnt--;
}
}
}
int max = 0, answer = 0;
for(int i = 0; i < n; i++) {
int sum = 0;
for(int j = 0; j < n; j++) {
sum += b[i][j];
}
if(max < sum) {
answer = i + 1;
max = sum;
}
}
return answer;
}
}
- Read the size of the matrix (n) from the user.
- Read the elements of the matrix from the user and store them in a 2D array a.
- Create a new 2D array b to store the count of repeated elements in each column.
- Iterate over each column of the matrix (a) and for each element, compare it with the elements in the same column. Increment the count in the corresponding position in the b array.
- Find the row with the maximum sum of counts in the b array. The row index (1-based) is considered the answer.
'Language > Algorithm' 카테고리의 다른 글
Count Consecutive Sums (0) | 2023.12.27 |
---|---|
Subarray Sum (0) | 2023.12.25 |
Array Analyzer (1) | 2023.12.19 |
Matrix Max Sum Program (1) | 2023.12.16 |
Element Ranking Code (0) | 2023.12.16 |