2965.找出缺失和重复的数字


2965.找出缺失和重复的数字

给你一个下标从 0 开始的二维整数矩阵 grid,大小为 n * n ,其中的值在 [1, n2] 范围内。除了 a 出现 两次b 缺失 之外,每个整数都 恰好出现一次

任务是找出重复的数字a 和缺失的数字 b

返回一个下标从 0 开始、长度为 2 的整数数组 ans ,其中 ans[0] 等于 aans[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 <= 50
  • 1 <= grid[i][j] <= n * n
  • 对于所有满足1 <= x <= n * nx ,恰好存在一个 x 与矩阵中的任何成员都不相等。
  • 对于所有满足1 <= x <= n * nx ,恰好存在一个 x 与矩阵中的两个成员相等。
  • 除上述的两个之外,对于所有满足1 <= x <= n * nx ,都恰好存在一对 i, j 满足 0 <= i, j <= n - 1grid[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;
    }
}

文章作者: Feliks
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Feliks !
评论
  目录