LeetCode //C - 2352. Equal Row and Column Pairs

2352. Equal Row and Column Pairs

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 < = g r i d [ i ] [ j ] < = 1 0 5 1 <= grid[i][j] <= 10^5 1<=grid[i][j]<=105

From: LeetCode
Link: 2352. Equal Row and Column Pairs


Solution:

Ideas:

This function counts the number of equal pairs by comparing each row with each column. If the elements in a row and column match for the entire length, it increments the count. This solution has a time complexity of O ( n 3 ) O(n^3) O(n3) which is acceptable given the constraints 1 ≤ n ≤ 200 1≤n≤200 1n200.

Code:
int equalPairs(int** grid, int gridSize, int* gridColSize) {
    int count = 0;
    for (int i = 0; i < gridSize; ++i) { // Iterate over rows
        for (int j = 0; j < gridSize; ++j) { // Iterate over columns
            int k;
            for (k = 0; k < gridSize; ++k) { // Check if row[i] equals column[j]
                if (grid[i][k] != grid[k][j]) {
                    break; // If any element does not match, break out of the loop
                }
            }
            if (k == gridSize) { // If we didn't break, the row and column are equal
                count++;
            }
        }
    }
    return count;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值