题目如下
给你两个非负整数数组 rowSum 和 colSum ,其中 rowSum[i] 是二维矩阵中第 i 行元素的和, colSum[j] 是第 j 列元素的和。换言之你不知道矩阵里的每个元素,但是你知道每一行和每一列的和。
请找到大小为 rowSum.length x colSum.length 的任意 非负整数 矩阵,且该矩阵满足 rowSum 和 colSum 的要求。
请你返回任意一个满足题目要求的二维矩阵,题目保证存在 至少一个 可行矩阵。
public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
int [][]arr=new int[rowSum.length][colSum.length];
for(int i = 0;i<rowSum.length;i++){
for(int j = 0;j<colSum.length;j++){
arr[i][j]=Math.min(rowSum[i],colSum[j]);
rowSum[i]-=arr[i][j];
colSum[j]-=arr[i][j];
if(rowSum[i]==0){
i++;
}
if(colSum[j]==0){
j++;
}
}
}
return arr;
}
这是我一开始写的代码,根据我的逻辑来看没有错可是最后提交的时候却出错了。
仔细回看代码我发现原因出在for循环上,由于我在下面给循环值i和j做了自增处理,当它继续循环的时候有些数据就会被跳过,所以我改成while循环。更改代码如下:
class Solution {
public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
int [][]arr=new int[rowSum.length][colSum.length];
int i=0,j=0;
while( i<rowSum.length&& j<colSum.length){
arr[i][j]=Math.min(rowSum[i],colSum[j]);
rowSum[i]-=arr[i][j];
colSum[j]-=arr[i][j];
if(rowSum[i]==0){
i++;
}
if(colSum[j]==0){
j++;
}
}
return arr;
}
}
第一次刷算法题,收获很大。