跳到主要内容

2352.相等行列对

链接:2352.相等行列对
难度:Medium
标签:数组、哈希表、矩阵、模拟
简介:给你一个下标从 0 开始、大小为 n x n 的整数矩阵 grid ,返回满足 Ri 行和 Cj 列相等的行列对 (Ri, Cj) 的数目。

题解 1 - cpp

  • 编辑时间:2023-06-06
  • 执行用时:224ms
  • 内存消耗:43MB
  • 编程语言:cpp
  • 解法介绍:哈希存储。
class Solution {
public:
int equalPairs(vector<vector<int>>& grid) {
unordered_map<string, int> rows;
int res = 0, n = grid.size();
for (int i = 0; i < n; i++) {
string key = "";
for (int j = 0; j < n; j++) key += to_string(grid[i][j]) + ",";
rows[key]++;
}
for (int j = 0; j < n; j++) {
string key = "";
for (int i = 0; i < n; i++) key += to_string(grid[i][j]) + ",";
res += rows[key];
}
return res;
}
};

题解 2 - python

  • 编辑时间:2023-06-06
  • 执行用时:212ms
  • 内存消耗:20.6MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
rows = Counter()
res = 0
n = len(grid)
for i in range(n):
key = ""
for j in range(n):
key += str(grid[i][j]) + ","
rows[key] += 1
for j in range(n):
key = ""
for i in range(n):
key += str(grid[i][j]) + ","
res += rows[key]
return res

题解 3 - rust

  • 编辑时间:2023-06-06
  • 执行用时:44ms
  • 内存消耗:3MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn equal_pairs(grid: Vec<Vec<i32>>) -> i32 {
let mut rows = std::collections::HashMap::<String, i32>::new();
let mut res = 0;
let n = grid.len();
for i in 0..n {
let mut key = String::new();
for j in 0..n {
key.push_str(&format!("{}", grid[i][j]));
key.push(',');
}
*rows.entry(key).or_insert(0) += 1;
}
for j in 0..n {
let mut key = String::new();
for i in 0..n {
key.push_str(&format!("{}", grid[i][j]));
key.push(',');
}
res += *rows.entry(key).or_insert(0);
}
res
}
}