2965.找出缺失和重复的数字
给你一个下标从 0 开始的二维整数矩阵 grid,大小为 n * n ,其中的值在 [1, n2] 范围内。除了 a 出现 两次,b 缺失 之外,每个整数都 恰好出现一次 。
任务是找出重复的数字a 和缺失的数字 b 。
返回一个下标从 0 开始、长度为 2 的整数数组 ans ,其中 ans[0] 等于 a ,ans[1] 等于 b 。
示例 1:
输入:grid = [[1,3],[2,2]]
输出:[2,4]
解释:数字 2 重复,数字 4 缺失,所以答案是 [2,4] 。
示例 2:
输入:grid = [[9,1,7],[8,9,2],[3,4,6]]
输出:[9,5]
解释:数字 9 重复,数字 5 缺失,所以答案是 [9,5] 。
提示:
2 <= n == grid.length == grid[i].length <= 501 <= grid[i][j] <= n * n- 对于所有满足
1 <= x <= n * n的x,恰好存在一个x与矩阵中的任何成员都不相等。 - 对于所有满足
1 <= x <= n * n的x,恰好存在一个x与矩阵中的两个成员相等。 - 除上述的两个之外,对于所有满足
1 <= x <= n * n的x,都恰好存在一对i, j满足0 <= i, j <= n - 1且grid[i][j] == x。
题解:
// class Solution {
// public int[] findMissingAndRepeatedValues(int[][] grid) {
// Map<Integer, Integer> map = new HashMap<>();
// for (int[] arr : grid) {
// for (int num : arr) {
// if (!map.containsKey(num)) {
// map.put(num, 1);
// } else {
// map.put(num, map.get(num) + 1);
// }
// }
// }
// int left = 1;
// int right = grid[0].length * grid[0].length;
// int[] res = new int[2];
// for (int i = left; i <= right; i++) {
// if (map.containsKey(i) && map.get(i) > 1) {
// res[0] = i;
// } else if (!map.containsKey(i)) {
// res[1] = i;
// }
// }
// return res;
// }
// }
class Solution {
public int[] findMissingAndRepeatedValues(int[][] grid) {
int[] count = new int[grid[0].length * grid[0].length + 1];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid.length; j++) {
count[grid[i][j]]++;
}
}
int[] res = new int[2];
for (int i = 1; i <= grid.length * grid.length; i++) {
if (count[i] == 2) {
res[0] = i;
}
if (count[i] == 0) {
res[1] = i;
}
}
return res;
}
}