Leetcode1252. Cells with Odd Values in a Matrix

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

猜你喜欢

转载自www.cnblogs.com/chengxian/p/12204030.html
今日推荐