|
| 1 | +/** |
| 2 | + * 1253. Reconstruct a 2-Row Binary Matrix |
| 3 | + * https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the following details of a matrix with n columns and 2 rows: |
| 7 | + * - The matrix is a binary matrix, which means each element in the matrix can be 0 or 1. |
| 8 | + * - The sum of elements of the 0-th(upper) row is given as upper. |
| 9 | + * - The sum of elements of the 1-st(lower) row is given as lower. |
| 10 | + * - The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an |
| 11 | + * integer array with length n. |
| 12 | + * |
| 13 | + * Your task is to reconstruct the matrix with upper, lower and colsum. |
| 14 | + * Return it as a 2-D integer array. |
| 15 | + * If there are more than one valid solution, any of them will be accepted. |
| 16 | + * If no valid solution exists, return an empty 2-D array. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} upper |
| 21 | + * @param {number} lower |
| 22 | + * @param {number[]} colsum |
| 23 | + * @return {number[][]} |
| 24 | + */ |
| 25 | +var reconstructMatrix = function(upper, lower, colsum) { |
| 26 | + const n = colsum.length; |
| 27 | + const matrix = [[], []]; |
| 28 | + let upperLeft = upper; |
| 29 | + let lowerLeft = lower; |
| 30 | + |
| 31 | + for (let i = 0; i < n; i++) { |
| 32 | + if (colsum[i] === 2) { |
| 33 | + matrix[0][i] = 1; |
| 34 | + matrix[1][i] = 1; |
| 35 | + upperLeft--; |
| 36 | + lowerLeft--; |
| 37 | + } else { |
| 38 | + matrix[0][i] = 0; |
| 39 | + matrix[1][i] = 0; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (upperLeft < 0 || lowerLeft < 0) return []; |
| 44 | + |
| 45 | + for (let i = 0; i < n; i++) { |
| 46 | + if (colsum[i] === 1) { |
| 47 | + if (upperLeft > 0) { |
| 48 | + matrix[0][i] = 1; |
| 49 | + matrix[1][i] = 0; |
| 50 | + upperLeft--; |
| 51 | + } else if (lowerLeft > 0) { |
| 52 | + matrix[0][i] = 0; |
| 53 | + matrix[1][i] = 1; |
| 54 | + lowerLeft--; |
| 55 | + } else { |
| 56 | + return []; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return upperLeft === 0 && lowerLeft === 0 ? matrix : []; |
| 62 | +}; |
0 commit comments