gpt4 book ai didi

java - 检查给定行列总和是否存在只有 2 行的二进制矩阵

转载 作者:行者123 更新时间:2023-12-02 10:17:07 25 4
gpt4 key购买 nike

我有一个只有 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;
}
}

最佳答案

差不多了,但是这里出了问题:

// Any one if the columns should be 1

仅考虑这一点意味着您的两个矩阵将满足 C 提供的条件,但不满足 AB 因为您只是交替出现 C[i] == 1 的情况。

最简单的情况:A = 2B = 0C = [1,1]。您的程序将打印 "10,01",而它应该是 "11,00"

所以这里的技巧是:处理完简单的 C[i] == 0C[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" 。如果有,请将其添加到底行。

关于java - 检查给定行列总和是否存在只有 2 行的二进制矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54608368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com