我有一个只有2行N列的二进制矩阵。
第一行元素的总和为A,第二行元素的总和为B。
列的总和存储在数组C中。
If A = 3, B = 2, C = [2,1,1,0,1] Then output is "11001,10100"
Explanation:
11001 = sum of 1st row is A = 3
10100 = sum of 2nd row is B = 2
21101 --> This is column sum which indicates Array C.
另一个例子:
If A = 2, B = 3, C = [0,0,1,1,2] Then output is "NO"
我写了下面的程序,该程序适用于上述测试用例,但是当我在面试中运行它时,它仅通过了40%的测试用例,请您能帮助我解决这个问题,该程序中的错误是什么?纠正这个问题?
public static String process(int A, int B, int[] C) {
int total = 0;
for (int val : C) {
total = total + val;
}
// Sums do not match so matrix is not possble
if (total != A + B) {
return "NO";
} else {
String first = "", second = "";
boolean flag = true;
for (int i = 0; i < C.length; i++) {
// Both the columns must be 1
if (C[i] == 2) {
first += "1";
second += "1";
} else if (C[i] == 0) {
// Both the columns must be 0
first += "0";
second += "0";
} else {
// Any one if the columns should be 1
if (flag) {
first += "1";
second += "0";
} else {
first += "0";
second += "1";
}
flag = !flag;
}
}
return first + "," + second;
}
}
答案 0 :(得分:1)
几乎,但是这里出了问题:
// Any one if the columns should be 1
仅考虑这将意味着您的两个矩阵将满足C
提供的条件,但不能满足A
和B
的条件,因为您只是为情况C[i] == 1
进行了交替
此中断最简单的情况:A = 2
,B = 0
和C = [1,1]
。您的程序将打印"10,01"
,而应打印"11,00"
。
因此,诀窍是:处理了简单的C[i] == 0
和C[i] == 2
案例之后,您必须弄清楚在第一行和第二行中还需要多少个1
编辑:可能的解决方案是:
boolean flag = true;
int currentTopRowSum = 0;
for (int i = 0; i < C.length; i++) {
// Both the columns must be 1
if (C[i] == 2) {
first += "1";
second += "1";
} else if (C[i] == 0) {
// Both the columns must be 0
first += "0";
second += "0";
} else {
//This is where it went wrong, so I changed this.
if (currentTopRowSum < A) {
first += "1";
second += "0";
currentTopRowSum++;
} else {
first += "0";
second += "1";
}
}
}
简而言之,您跟踪第一行的总和,如果尚未达到该标准,则在其中加上"1"
。如果有的话,请将其添加到底部一行。