Given the following details of a matrix with n
columns and 2
rows :
- The matrix is a binary matrix, which means each element in the matrix can be
0
or1
. - The sum of elements of the 0-th(upper) row is given as
upper
. - The sum of elements of the 1-st(lower) row is given as
lower
. - The sum of elements in the i-th column(0-indexed) is
colsum[i]
, wherecolsum
is given as an integer array with lengthn
.
Your task is to reconstruct the matrix with upper
, lower
and colsum
.
Return it as a 2-D integer array.
If there are more than one valid solution, any of them will be accepted.
If no valid solution exists, return an empty 2-D array.
Example 1:
Input: upper = 2, lower = 1, colsum = [1,1,1] Output: [[1,1,0],[0,0,1]] Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.
Example 2:
Input: upper = 2, lower = 3, colsum = [2,2,1,1] Output: []
Example 3:
Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1] Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]
class Solution { List<List<Integer>> res; public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) { res = new ArrayList<>(); int n = colsum.length; List<Integer> first = new ArrayList<>(); List<Integer> second = new ArrayList<>(); for (int i = 0; i < n; i++) { if (colsum[i] == 2) { first.add(1); second.add(1); upper--; lower--; } else if (colsum[i] == 0) { first.add(0); second.add(0); } else { if (upper > lower) { first.add(1); upper--; second.add(0); } else { second.add(1); lower--; first.add(0); } } if (upper < 0 || lower < 0) { return res; } } if (lower == 0 && upper == 0) { res.add(first); res.add(second); } return res; } }
简化版的:
class Solution { public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) { int[][] res = new int[2][colsum.length]; for(int i = 0; i < colsum.length; i++){ res[0][i] = (colsum[i] == 2 || (colsum[i] == 1 && lower < upper)) ? 1 : 0; res[1][i] = (colsum[i] == 2 || (colsum[i] == 1 && res[0][i] != 1)) ? 1 : 0; upper -= (res[0][i] == 1) ? 1 : 0; lower -= (res[1][i] == 1) ? 1 : 0; } return lower == 0 && upper == 0 ? new ArrayList(Arrays.asList(res[0], res[1])) : new ArrayList(); } }
意思是重造数组,upper和lower表示行的sum,colsum数组顾名思义
所以colsum的值等于2时两个数组都为1,如果等于1则让lower或upper中大的一个为1,因为有且只有一种可能。
最后判断upper和lower是不是等于0,如果是就成功,否则失败。