- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path2352-equal-row-and-column-pairs.rb
59 lines (49 loc) · 1.5 KB
/
2352-equal-row-and-column-pairs.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true
# 2352. Equal Row and Column Pairs
# https://leetcode.com/problems/equal-row-and-column-pairs
# Medium
=begin
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:
Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]
Example 2:
Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]
Constraints:
n == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105
=end
# @param {Integer[][]} grid
# @return {Integer}
defequal_pairs(grid)
row_counts=Hash.new(0)
col_counts=Hash.new(0)
result=0
grid.each{ |el| row_counts[el] += 1}
grid.size.times{ |i| col_counts[grid.map{ |el| el[i - 1]}] += 1}
row_counts.eachdo |key,value|
if !col_counts[key].nil?
result += value * col_counts[key]
end
end
result
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_equal_pairs < Test::Unit::TestCase
deftest_
assert_equal1,equal_pairs([[3,2,1],[1,7,6],[2,7,7]])
assert_equal3,equal_pairs([[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]])
end
end