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] { // 左上 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) // 右下 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(a, b int)int { if a < b { return b - a } return a - b }
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)) // ans[i-1][j-1]为左上个数, len(set)为右下个数,这里直接求解了 } } return ans }
funcmaxIncreasingCells(mat [][]int)int { type pair struct { x, y int } g := make(map[int][]pair) for i, row := range mat { for j, x := range row { g[x] = append(g[x], pair{i, j}) } } keys := make([]int, 0) for k := range g { keys = append(keys, k) } sort.Ints(keys) rowMax := make([]int, len(mat)) colMax := make([]int, len(mat[0])) var ans int for _, x := range keys { pos := g[x] mx := make([]int, len(pos)) for i, p := range pos { mx[i] = max(rowMax[p.x], colMax[p.y]) + 1// 先把最大值算出来,再更新 rowMax 和 colMax ans = max(ans, mx[i]) } for i, p := range pos { rowMax[p.x] = max(rowMax[p.x], mx[i]) // 更新第 p.x 行的最大值 colMax[p.y] = max(colMax[p.y], mx[i]) // 更新第 p.y 列的最大值 } } return ans }