给你一个下标从 0 开始的二维整数矩阵 grid,大小为 n * n ,其中的值在 [1, n2] 范围内。除了 a 出现 两次,b 缺失 之外,每个整数都 恰好出现一次 。
任务是找出重复的数字a 和缺失的数字 b 。
返回一个下标从 0 开始、长度为 2 的整数数组 ans ,其中 ans[0] 等于 a ,ans[1] 等于 b 。
/*** Note: The returned array must be malloced, assume caller calls free().*/ int* findMissingAndRepeatedValues(int** grid, int gridSize, int* gridColSize, int* returnSize) {int n = gridSize;int* count = (int *)calloc(n * n + 1, sizeof(int));for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {count[grid[i][j]]++;}}*returnSize = 2;int *res = (int *)malloc(2 * sizeof(int));for (int i = 1; i <= n * n; i++) {if (count[i] == 2) {res[0] = i;}if (count[i] == 0) {res[1] = i;}}free(count);return res;
}
解题思路:利用空间存储再遍历,找到所要求的值再输出