-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1253. Reconstruct a 2-Row Binary Matrix
More file actions
45 lines (44 loc) · 1.63 KB
/
Copy path1253. Reconstruct a 2-Row Binary Matrix
File metadata and controls
45 lines (44 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Problem Link : https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/
--------------------------------------------------------------------------------
Complexity : Time-O(N), Memory-O(1), TimeTaken-<6hr
--------------------------------------------------------------------------------
Logic :
So the logic is that at each col[i] where its sum is 2 we place 1 in both row
if 1 then we see which row sum is greater and act accordingly.
And for the impossible
part after the nth col processing we see if upper & lower !=0 it either means value was
not assigned fully or needed more value in that case return empty list.
class Solution {
public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {
List<List<Integer>> ans=new ArrayList();
ans.add(new ArrayList());
ans.add(new ArrayList());
int n=colsum.length;
for(int i=0;i<n;i++){
if(colsum[i]==0){
ans.get(0).add(0);
ans.get(1).add(0);
} else if(colsum[i]==2){
upper--;
lower--;
ans.get(0).add(1);
ans.get(1).add(1);
} else {
if(upper>lower){
upper--;
ans.get(0).add(1);
ans.get(1).add(0);
} else {
lower--;
ans.get(0).add(0);
ans.get(1).add(1);
}
}
if(upper<0 || lower<0)
return new ArrayList();
}
if(upper!=0 || lower!=0)
return new ArrayList();
return ans;
}
}