Every day a Leetcode
题目来源:2965. 找出缺失和重复的数字
解法1:哈希
用哈希表统计数组 grid 中各元素的出现次数,其中出现次数为 2 的记为 a。
统计数组 grid 的元素之和为 sum。
数组 grid 其中的值在 [1, n2] 范围内,和为 n2*(n2+1)/2。
当 sum > n * n * (n * n + 1) / 2 时,b = a - (sum - n * n * (n * n + 1) / 2)
;否则,b = a + (n * n * (n * n + 1) / 2 - sum)
。
代码:
/** @lc app=leetcode.cn id=2965 lang=cpp** [2965] 找出缺失和重复的数字*/// @lc code=start
class Solution
{
public:vector<int> findMissingAndRepeatedValues(vector<vector<int>> &grid){if (grid.empty())return {};int n = grid.size();int sum = 0, a = 0, b = 0;unordered_map<int, int> hash;for (int i = 0; i < n; i++)for (int j = 0; j < n; j++){int num = grid[i][j];hash[num]++;sum += num;if (hash[num] == 2)a = num;}if (sum > n * n * (n * n + 1) / 2)b = a - (sum - n * n * (n * n + 1) / 2);elseb = a + (n * n * (n * n + 1) / 2 - sum);return {a, b};}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n2),其中 n 是二维数组 grid 的长度。
空间复杂度:O(n2),其中 n 是二维数组 grid 的长度。