【发布时间】:2019-02-09 16:47:28
【问题描述】:
我有一个只有 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;
}
}
【问题讨论】: