Open songyy5517 opened 4 months ago
Approach: HashMap
Complexity Analysis
class Solution {
public int equalPairs(int[][] grid) {
// Intuition: HashMap.
// 1. Exception Handling
if (grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
// 2. Record all the rows and their occurences.
HashMap<ArrayList, Integer> cols = new HashMap();
for (int j = 0; j < grid[0].length; j++){
ArrayList<Integer> col = new ArrayList();
for (int i = 0; i < grid.length; i++)
col.add(grid[i][j]);
cols.put(col, 1 + cols.getOrDefault(col, 0));
}
// 3. Loop through the columns and calculate the number of same pairs
int res = 0;
for (int i = 0; i < grid.length; i++){
ArrayList<Integer> row = new ArrayList();
for (int j = 0; j < grid[0].length; j++){
row.add(grid[i][j]);
}
if (cols.containsKey(row))
res += cols.get(row);
}
return res;
}
}
2024/5/17
Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal. A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
Example 1:
Example 2:
Intuition The problem is to find the number of equal row-column pairs. A simple idea is to store all the columns and their corresponding occurences in a hashmap. Then looping though the matrix by row, for each row, if it exists in the hashmap, then update the number of equal pairs.