Cells with Odd Values in a Matrix
给一个2d数组, 里面是横竖的index, 求在index上+1后matrix的奇数个数. 这个题我看有O(n)解法, 我自己做的是n^2
class Solution {
public int oddCells(int n, int m, int[][] indices) {
int[] row = new int[n];
int[] col = new int[m];
for(int[] i : indices) {
row[i[0]]++;
col[i[1]]++;
}
int count = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++){
if((row[i]+col[j]) % 2 != 0)
count++;
}
}
return count;
}
}
class Solution {
public int oddCells(int n, int m, int[][] indices) {
int[] row = new int[n];
int[] col = new int[m];
for(int[] i : indices) {
row[i[0]]++;
col[i[1]]++;
}
int count = 0;
for(int i = 0; i < n; i++) {
if(row[i] % 2 != 0) // if odd
count++;
}
int res = 0;
for(int i = 0; i < m; i++) {
if(col[i] % 2 != 0) // if odd
res += (n - count); // odd + odd = even
else
res += count;// odd + even = odd
}
return res;
}
}