|
| 1 | +/** |
| 2 | + * 2711. Difference of Number of Distinct Values on Diagonals |
| 3 | + * https://leetcode.com/problems/difference-of-number-of-distinct-values-on-diagonals/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a 2D grid of size m x n, you should find the matrix answer of size m x n. |
| 7 | + * |
| 8 | + * The cell answer[r][c] is calculated by looking at the diagonal values of the cell grid[r][c]: |
| 9 | + * - Let leftAbove[r][c] be the number of distinct values on the diagonal to the left and above |
| 10 | + * the cell grid[r][c] not including the cell grid[r][c] itself. |
| 11 | + * - Let rightBelow[r][c] be the number of distinct values on the diagonal to the right and below |
| 12 | + * the cell grid[r][c], not including the cell grid[r][c] itself. |
| 13 | + * - Then answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|. |
| 14 | + * |
| 15 | + * A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost |
| 16 | + * row or leftmost column and going in the bottom-right direction until the end of the matrix |
| 17 | + * is reached. |
| 18 | + * |
| 19 | + * - For example, in the below diagram the diagonal is highlighted using the cell with indices |
| 20 | + * (2, 3) colored gray: |
| 21 | + * - Red-colored cells are left and above the cell. |
| 22 | + * - Blue-colored cells are right and below the cell. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + *@param {number[][]} grid |
| 27 | + *@return {number[][]} |
| 28 | + */ |
| 29 | +vardifferenceOfDistinctValues=function(grid){ |
| 30 | +constrows=grid.length; |
| 31 | +constcols=grid[0].length; |
| 32 | +constresult=Array.from({length:rows},()=>newArray(cols).fill(0)); |
| 33 | + |
| 34 | +for(letr=0;r<rows;r++){ |
| 35 | +for(letc=0;c<cols;c++){ |
| 36 | +constleftAboveSet=newSet(); |
| 37 | +leti=r-1; |
| 38 | +letj=c-1; |
| 39 | +while(i>=0&&j>=0){ |
| 40 | +leftAboveSet.add(grid[i--][j--]); |
| 41 | +} |
| 42 | + |
| 43 | +constrightBelowSet=newSet(); |
| 44 | +i=r+1; |
| 45 | +j=c+1; |
| 46 | +while(i<rows&&j<cols){ |
| 47 | +rightBelowSet.add(grid[i++][j++]); |
| 48 | +} |
| 49 | + |
| 50 | +result[r][c]=Math.abs(leftAboveSet.size-rightBelowSet.size); |
| 51 | +} |
| 52 | +} |
| 53 | + |
| 54 | +returnresult; |
| 55 | +}; |