首页 > 其他 > 详细

Leetcode1252. Cells with Odd Values in a Matrix

时间:2020-01-17 10:41:59      阅读:74      评论:0      收藏:0      [点我收藏+]
public int oddCells(int n, int m, int[][] indices) {
int[][] Array = new int[n][m];
int rowlength = indices.length; //求出indices数组行数
for (int i = 0; i < rowlength; i++) { //开始分别对每个索引的行列进行增加
for (int j = 0; j < m; j++) {//先对行加
Array[indices[i][0]][j]+=1;
}
for(int k=0;k<n;k++){//再对列加
Array[k][indices[i][1]]+=1;
}
}
//统计里面偶数个数
int odd=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
if (Array[i][j]%2==1)
odd++;
}
System.out.println(odd);
return odd;
}
方法时间复杂度极低

技术分享图片

 

 Solutions:

后来发现规律

其实根本不用求出矩阵中的元素

只需要根据行变换和列变换次数,既可以得出奇数和偶数

public int oddCells(int n, int m, int[][] indices) {
int[] row = new int[n];
int[] col = new int[m];
for (int i = 0; i < indices.length; i++) {
row[indices[i][0]] += 1;
col[indices[i][1]] += 1;
}
int odd = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if ((row[i] + col[j]) % 2 == 1)
odd++;
}
System.out.println(odd);
return odd;
}

Leetcode1252. Cells with Odd Values in a Matrix

原文:https://www.cnblogs.com/chengxian/p/12204030.html

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