有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java根据行和列和还原01矩阵

请注意: 这个问题很长,可能需要花费一些时间阅读:

我在一次编码测试中遇到了这个问题:

Say we have a 0-1 matrix with 2 rows and N columns, given the U=the sum of upper row, and the L=the sum of low row, and int[] C= the array containing the sum of each column, return the String representation of the matrix. If there are more than one, return any of them. If no matrix satisfies, return "IMPOSSIBLE".

例1:

U=3,L=2,C=[2,1,1,0,1] return String="11100,10001"(two rows are seperated by ",")

通过以下方法,我得到了50%的正确率和14%的速度:

我的想法是:

  1. if U+L != the sum of elements in C, return "IMPOSSIBLE";
  2. otherwise, initilize the matrix with 0, and use a for loop to visit each element in C:
    if C[i]==2, set elements in each row with 1;
    if C[i]==0 set elements in each row with 0;
    if C[i]==1 && 0<U, set element in upper row with 1 and element in low row with 0, and U--,
    otherwise, set element in upper row with 0 and element in low row with 1;
  3. finally we visit each elemenet in the matrix to get the result String(with StringBuilder.append()).

谁能帮我改进一下吗? 经过长时间的思考,我想不出更好的解决方案。 我认为这个解决方案应该是100%正确的,O(N)应该是分钟时间复杂度,其中N是矩阵元素的总数


----更新:

class Solution {
public String solution(int U, int L, int[] C) {
    // write your code in Java SE 8
    int N=C.length;

    int colSum=0;
    for(int i=0;i<N;i++){
        colSum+=C[i];
    }
    if(colSum!=U+L){
        return "IMPOSSIBLE";
    }


    String[] upRow=new String[N];
    String[] lowRow=new String[N];
    for(int i=0;i<N;i++){
        if(C[i]==2){
            upRow[i]="1";
            lowRow[i]="1";
            U--;
            L--;
        }else if(C[i]==0){
            upRow[i]="0";
            lowRow[i]="0";
        }else{
            if(0<U){
                upRow[i]="1";
                lowRow[i]="0";
                U--;
            }else{
                upRow[i]="0";
                lowRow[i]="1";       
            }           
        }
    }

    StringBuilder sb=new StringBuilder();
    for(int i=0;i<N;i++){
        sb.append(upRow[i]);
    }
    sb.append(",");
    for(int i=0;i<N;i++){
        sb.append(lowRow[i]);
    }
    return sb.toString();
}

}


共 (0) 个答案