数组:[1252. 奇数值单元格的数目]

这是我的第二道lc题,这回能看懂题 ,但是智商限制了我的发挥,这个行与列的增长规则差点把自己绕丝,有时候,真的觉得自己笨的生气。

大致题意:

根据传入参数n,m(对应行与列)生成一个矩阵数组,对矩阵数组中的数据进行全行和全列加1,参数二位数组中包含多次指定的行与列,加1操都完成返回矩阵数组中的奇数值。

输入:n = 2, m = 3, indices = [[0,1],[1,1]]
输出:6
解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。
第一次增量操作后得到 [[1,2,1],[0,1,0]]。
最后的矩阵是 [[1,3,1],[1,3,1]],里面有 6 个奇数。

第一次代码:

 1 import java.lang.*;
 2 public class Solution {
 3      public static int oddCells(int n, int m, int[][] indices) {// 2,3
 4      int result=0;
 5          int size=n*m;
 6          int[]numArr=new int[size];
 7          for(int j=0;j<size;j++){
 8              numArr[j]=0;
 9          }
10        for(int i=0;i<indices.length;i++){
11            int hang=indices[i][0]; //0,1  1,1
12            int lie=indices[i][1]; 
13            for(int h=0;h<m;h++){
14                int index=m*hang+h;
15                ++numArr[index]; 
16            }
17            for(int l=0;l<n;l++){
18                int index=m*l+lie;
19                ++numArr[index]; 
20            }
21        }
22        for(int x=0;x<numArr.length;x++){
23            if(numArr[x]%2!=0){
24                result++;
25            };
26        }
27         return result;
28     }
29     public static void main(String[] args){
30         int [][]arr=new int[][]{{0,1},{1,1}};
31         int res=oddCells(2,3,arr);
32         System.out.print(res);
33     }
34 }

最终代码:

 1      public static int oddCells(int n, int m, int[][] indices) {
 2          int result=0;
 3          int[]numArr=new int[n*m];
 4        for(int i=0;i<indices.length;i++){
 5            for(int h=0;h<m;h++){
 6                int index=m*indices[i][0]+h;
 7                ++numArr[index]; 
 8            }
 9            for(int l=0;l<n;l++){
10                int index=m*l+indices[i][1];
11                ++numArr[index]; 
12            }
13        }
14        for(int x=0;x<numArr.length;x++){
15            if(numArr[x]%2!=0){
16                result++;
17            };
18        }
19         return result;
20     }

想把最下面的奇数个数判断放到+1的循环中,需要找到重叠加1的规律

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix

原文地址:https://www.cnblogs.com/fangyanr/p/11995860.html