classSolution: defdifferenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * n for _ inrange(m)] for i inrange(m): for j inrange(n): # topLeft s = set() x, y = i - 1, j - 1 while x >= 0and y >= 0: s.add(grid[x][y]) x -= 1 y -= 1 sz = len(s)
# bottomRight s.clear() x, y = i + 1, j + 1 while x < m and y < n: s.add(grid[x][y]) x += 1 y += 1 ans[i][j] = abs(sz - len(s)) return ans
funcdifferenceOfDistinctValues(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) ans := make([][]int, m) for i := range ans { ans[i] = make([]int, n) for j := range ans[i] { // topLeft set := map[int]struct{}{} for x, y := i-1, j-1; x >= 0 && y >= 0; { set[grid[x][y]] = struct{}{} x-- y-- } sz := len(set) // bottomRight set = map[int]struct{}{} for x, y := i+1, j+1; x < m && y < n; { set[grid[x][y]] = struct{}{} x++ y++ } ans[i][j] = abs(sz - len(set)) } } return ans }
funcabs(x int)int { if x < 0 { return -x }; return x }
复杂度分析
时间复杂度:\mathcal{O}(mn\cdot \min(m,n)),其中 m 和 n 分别为 grid 的行数和列数。
classSolution: defdifferenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * n for _ inrange(m)] for k inrange(1, m + n): min_j = max(n - k, 0) max_j = min(m + n - 1 - k, n - 1) # topLeft s = set() for j inrange(min_j, max_j): i = k + j - n s.add(grid[i][j]) ans[i + 1][j + 1] = len(s) # bottomRight s.clear() for j inrange(max_j, min_j, -1): i = k + j - n s.add(grid[i][j]) ans[i - 1][j - 1] = abs(ans[i - 1][j - 1] - len(s)) return ans
funcdifferenceOfDistinctValues(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) ans := make([][]int, m) for i := range ans { ans[i] = make([]int, n) } for s := 1; s < m+n; s++ { minJ := max(0, n-s) maxJ := min(n-1, n-s+m-1) // topLeft set := map[int]struct{}{} for j := minJ; j < maxJ; j++ { i := s + j - n set[grid[i][j]] = struct{}{} ans[i+1][j+1] = len(set) } // bottomRight set = map[int]struct{}{} for j := maxJ; j > minJ; j-- { i := s + j - n set[grid[i][j]] = struct{}{} ans[i-1][j-1] = abs(ans[i-1][j-1] - len(set)) } } return ans }
funcabs(x int)int { if x < 0 { return -x }; return x } funcmin(a, b int)int { if b < a { return b }; return a } funcmax(a, b int)int { if b > a { return b }; return a }
复杂度分析
时间复杂度:\mathcal{O}(mn),其中 m 和 n 分别为 grid 的行数和列数。每个单元格至多访问两次。