-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid matrix.cpp
35 lines (32 loc) · 1.2 KB
/
valid matrix.cpp
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
class Solution {
public:
vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
int rows = rowSum.size();
int cols = colSum.size();
int cur_row = 0, cur_col = 0;
vector<vector<int>> res(rows, vector<int>(cols, 0));
while (cur_row < rows || cur_col < cols) {
if (cur_row >= rows) {
res[rows - 1][cur_col] = colSum[cur_col];
cur_col++;
continue;
} else if (cur_col >= cols) {
res[cur_row][cols - 1] = rowSum[cur_row];
cur_row++;
continue;
}
int value_to_put = min(rowSum[cur_row], colSum[cur_col]);
rowSum[cur_row] -= value_to_put;
colSum[cur_col] -= value_to_put;
res[cur_row][cur_col] = value_to_put;
// I write this as this because it's possible that rowSum[cur_row] == colSum[cur_col] and we'll want to move both row and col pointers
if (rowSum[cur_row] == 0) {
cur_row++;
}
if (colSum[cur_col] == 0) {
cur_col++;
}
}
return res;
}
};