[LeetCode one question per day] [Medium]861. Score after flipping the matrix

[LeetCode one question per day] [Medium]861. Score after flipping the matrix

861. Score after flipping the matrix

861. Score after flipping the matrix

Algorithm thought: Greedy

topic:

Insert picture description here

java code

Idea: The number should be as large as possible. If the first column of each row is 1 (flip the row), the remaining columns should be as large as possible to make the number of 1s (flip the column)
as follows: Binary conversion:
Insert picture description here

  1. First, see if the first column is 1, if it is not flipped; also record the result
  2. Follow-up traversal by column; count the number of 0/1, use the larger number to calculate the column
class Solution {
    
    
    public int matrixScore(int[][] A) {
    
    
        int sum = 0;//返回的总和
        //尽可能大,0列要为1,如果不是1,翻转行
        for (int i = 0; i < A.length; i++) {
    
    
            if(A[i][0] == 0) {
    
    
                for (int j = 0; j < A[i].length; j++) {
    
    //翻转该行
                    if(A[i][j] == 0) {
    
    
                        A[i][j] = 1;
                    }else {
    
    
                        A[i][j] = 0;
                    }
                }
            }
            sum += Math.pow(2,A[i].length - 1);//累加计算为0列数字总和
        }
        int j = 1;//从1列开始
        while(j < A[0].length) {
    
    
            int zeroNum = 0;//统计该列0的数量
            int oneNum = 0;//统计该列1的数量
            for (int i = 0; i < A.length; i++) {
    
    
                if(A[i][j] == 0) {
    
    
                    zeroNum++;
                }else {
    
    
                    oneNum++;
                }
            }
            if(zeroNum > oneNum) {
    
    //如果0的数量更多,进行该列翻转,即统计0的数量作为1的数量
                oneNum = zeroNum;
            }
            sum += oneNum * Math.pow(2,A[0].length - j - 1);//累加计算为j列数字总和
            j++;//下一列
        }

        return sum;
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/110823793