zoukankan      html  css  js  c++  java
  • 1252. Cells with Odd Values in a Matrix

    Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

    Return the number of cells with odd values in the matrix after applying the increment to all indices.

    Example 1:

    Input: n = 2, m = 3, indices = [[0,1],[1,1]]
    Output: 6
    Explanation: Initial matrix = [[0,0,0],[0,0,0]].
    After applying first increment it becomes [[1,2,1],[0,1,0]].
    The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.
    

    Example 2:

    Input: n = 2, m = 2, indices = [[1,1],[0,0]]
    Output: 0
    Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.
    

    Constraints:

    • 1 <= n <= 50
    • 1 <= m <= 50
    • 1 <= indices.length <= 100
    • 0 <= indices[i][0] < n
    • 0 <= indices[i][1] < m
    class Solution {
        public int oddCells(int n, int m, int[][] indices) {
            int[][] res = new int[n][m];
            for(int i = 0; i < n; i++) Arrays.fill(res[i], 0);
            for(int i = 0; i < indices.length; i++){
                int r = indices[i][0];
                int c = indices[i][1];
                for(int j = 0; j < m; j++) res[r][j]++;
                for(int j = 0; j < n; j++) res[j][c]++;
            }
            int re = 0;
            for(int i = 0; i < n; i++){
                for(int j = 0; j < m; j++){
                    if(res[i][j] % 2 != 0) re++;
                }
            }
            return re;
        }
    }

    题意思是初始给一个全0数组,然后给一个indices数组里面的ri,ci表示row和column,然后在该row,column每个increment1.最后算数组有几个odd

    另一种方法

    class Solution {
        public int oddCells(int n, int m, int[][] indices) {
            if(n <= 0 || m <= 0 || indices == null || indices.length == 0 || indices[0].length == 0) return 0;
            
            int[] rows = new int[n];
            int[] clms = new int[m];
            
            
            for(int i = 0; i < indices.length; i++){
                int[] rc = indices[i];
                rows[rc[0]]++;
                clms[rc[1]]++;
            }
    
            int ret = 0;
            for(int r = 0; r < rows.length; r++){
                for(int c = 0; c < clms.length; c++){
                    if((rows[r] + clms[c]) % 2 == 1){
                        ret++;
                    }
                }
            }
                  
            return ret;       
        }
    }

    一维数组比二维数组快,学到了。

  • 相关阅读:
    8.26 Linux的目录机构与目录管理
    8.26 基础命令
    8.26 系统基础
    8.26 课程介绍
    8.21-23 awk
    8.20 数组与字符
    8.19 函数
    8.16 sed命令
    Linux操作系统--初级--Linux的目录结构与目录管理
    Linux操作系统--初级--基础命令
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11870425.html
Copyright © 2011-2022 走看看