首页 > 其他 > 详细

1252. Cells with Odd Values in a Matrix

时间:2019-11-16 09:04:32      阅读:96      评论:0      收藏:0      [点我收藏+]

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;       
    }
}

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

1252. Cells with Odd Values in a Matrix

原文:https://www.cnblogs.com/wentiliangkaihua/p/11870425.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!