Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3e4e549

Browse files
ac 2352
1 parent 91b548a commit 3e4e549

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* Copyright (C) 2023, Saul Lawliet <october dot sunbathe at gmail dot com>
3+
* All rights reserved.
4+
*
5+
* 直观感觉这道题不应该算中等难度, 解题的过程中有两个问题
6+
* 1. hash越界
7+
* 解决方法: 对10000007取模
8+
* 2. hash一致但数组不相等
9+
* 解决方法: hash一致的情况也继续对比数组是否相等
10+
*/
11+
12+
#include "c/data-structures/array.h"
13+
#include "c/test.h"
14+
15+
int equalPairs(int **grid, int gridSize, int *gridColSize) {
16+
int *rowHash = malloc(sizeof(int) * gridSize);
17+
int *colHash = malloc(sizeof(int) * gridSize);
18+
19+
for (int i = 0; i < gridSize; i++) {
20+
rowHash[i] = 1;
21+
colHash[i] = 1;
22+
}
23+
24+
for (int i = 0; i < gridSize; i++) {
25+
for (int j = 0; j < gridSize; j++) {
26+
rowHash[i] = (rowHash[i] * 31 + grid[i][j]) % 10000007;
27+
colHash[i] = (colHash[i] * 31 + grid[j][i]) % 10000007;
28+
}
29+
}
30+
31+
int rt = 0;
32+
for (int i = 0; i < gridSize; i++) {
33+
for (int j = 0; j < gridSize; j++) {
34+
if (rowHash[i] == colHash[j]) {
35+
// hash 一致, 也要对比每一项
36+
for (int k = 0; k < gridSize; k++) {
37+
if (grid[i][k] != grid[k][j]) break;
38+
if (k == gridSize - 1) rt++;
39+
}
40+
}
41+
}
42+
}
43+
44+
free(colHash);
45+
free(rowHash);
46+
47+
return rt;
48+
}
49+
50+
void test(int except, char *grid) {
51+
arrayEntry *e = arrayParse2D(grid, ARRAY_INT);
52+
EXPECT_EQ_INT(except, equalPairs(arrayValue(e), arrayRow(e), arrayCols(e)));
53+
arrayFree(e);
54+
}
55+
56+
int main(void) {
57+
test(1, "[[3,2,1],[1,7,6],[2,7,7]]");
58+
test(3, "[[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]");
59+
test(0, "[[2,1],[3,32]]");
60+
61+
return testOutput();
62+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /