# 1253. Reconstruct a 2-Row Binary Matrix ###### tags: `Leetcode` `Medium` `Greedy` Link: https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/ ## 思路 遍历colsum 如果colsum=2 说明upper和lower都要放 如果colsum=1 则需要考虑一下放哪边 因为后面出现2的时候 upper和lower都要放 消耗的数量一样 因此当下upper和lower哪个剩的多就把1放在哪边 如果把```lower<upper```改成```upper!=0```,就有可能出现最后遍历完upper=-2 lower=2的情况 ## Code ```java= 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]; lower -= res[1][i]; } return upper==0 && lower==0 ? new ArrayList(Arrays.asList(res[0], res[1])) : new ArrayList(); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up