Advertisement
ogv

Untitled

ogv
Nov 13th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. // Runtime: 0 ms, faster than 100.00% of Java online submissions for Score After Flipping Matrix.
  2. class Solution {
  3.     int[][] a;
  4.     int m;
  5.     int n;
  6.     public int matrixScore(int[][] A) {
  7.         a = A;
  8.         m = a.length;
  9.         n = a[0].length;
  10.                
  11.         for (int r = 0; r < m; r++)
  12.             if (a[r][0] == 0) flipRow(r);
  13.        
  14.         for (int c = 0; c < n; c++) {            
  15.             int ones = 0;
  16.             for (int r = 0; r < m; r++)
  17.                 if (a[r][c] == 1) ones++;
  18.            
  19.             if (ones <= m/2) flipColumn(c);                            
  20.         }
  21.        
  22.         return score();
  23.     }
  24.    
  25.     private int score() {
  26.         int sum = 0;
  27.        
  28.         for (int r = 0; r < m; r++) {
  29.             int num = 0;
  30.             int p = 1;
  31.             for (int c = n-1; c >= 0; c--){
  32.                 if (a[r][c] == 1) num += p;
  33.                 p <<= 1;
  34.             }
  35.             sum += num;
  36.         }
  37.        
  38.         return sum;
  39.     }
  40.    
  41.     private void flipColumn(int c) {
  42.         for (int r = 0; r < m; r++) a[r][c] = 1 - a[r][c];
  43.     }
  44.    
  45.     private void flipRow(int r) {
  46.         for (int c = 0; c < n; c++) a[r][c] = 1 - a[r][c];
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement