2965. Find Missing and Repeated Values
You are given a 0-indexed 2D integer matrix
gridof sizen * nwith values in the range[1, n2]. Each integer appears exactly once exceptawhich appears twice andbwhich is missing. The task is to find the repeating and missing numbersaandb.Return a 0-indexed integer array
ansof size2whereans[0]equals toaandans[1]equals tob.Example 1:
Input: grid = [[1,3],[2,2|1,3],[2,2]]
Output: [2,4]
Explanation: Number 2 is repeated and number 4 is missing so the answer is [2,4].Example 2:
Input: grid = [[9,1,7],[8,9,2],[3,4,6|9,1,7],[8,9,2],[3,4,6]]
Output: [9,5]
Explanation: Number 9 is repeated and number 5 is missing so the answer is [9,5].Constraints:
2 <= n == grid.length == grid[i].length <= 501 <= grid[i][j] <= n * n- For all
xthat1 <= x <= n * nthere is exactly onexthat is not equal to any of the grid members.- For all
xthat1 <= x <= n * nthere is exactly onexthat is equal to exactly two of the grid members.- For all
xthat1 <= x <= n * nexcept two of them there is exactly one pair ofi, jthat0 <= i, j <= n - 1andgrid[i][j] == x.
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
l = len(grid)
n = [1] * (l*l)
for i in grid:
for j in i:
if n[j-1] == 0:
repeated = j
else:
n[j-1] = 0
return [repeated, n.index(1)+1]