public class Solution {
public int OddCells(int n, int m, int[][] indices) {
var mat = new int[n, m];
foreach (var index in indices) {
var ri = index[0];
for (var col = 0; col < m; ++col) {
++mat[ri, col];
}
var ci = index[1];
for (var row = 0; row < n; ++row) {
++mat[row, ci];
}
}
// functional programming:
// return mat.Cast<int>().Count(number => number % 2 == 1);
// this would work:
// var oddCount = 0;
// for (var ni = 0; ni < n; ++ni) {
// for (var mi = 0; mi < m; ++mi) {
// oddCount += mat[ni, mi] % 2;
// }
// }
// this is better and faster. C# can look at array as if it is one-dimensional
var oddCount = 0;
foreach (var number in mat) {
oddCount += number % 2;
}
return oddCount;
}
}
Source: https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/
"Simplicity can't be bought later, it must be earned from the start" -- DB
No comments:
Post a Comment