【问题标题】:Check if binary matrix exists with only 2 rows for given row and column sum检查给定行和列总和是否只有 2 行的二进制矩阵
【发布时间】: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;
    }
}

【问题讨论】:

    标签: java matrix


    【解决方案1】:

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

    // 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 案例之后,你必须弄清楚第一行和第二行还有多少1s。

    编辑:一个可能的解决方案是:

    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"。如果有,请将其添加到最后一行。

    【讨论】:

    • 你能帮我写这个逻辑来找到所有可能的集合吗?
    • 当然,检查我的答案。它没有提供所有可能的解决方案,但它会在给定约束 À, Band C` 的情况下提供正确的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2019-10-15
    • 2014-07-19
    • 2021-12-30
    • 2023-04-08
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多