Friday, February 26, 2021

Leetcode Everyday: 1252. Cells with Odd Values in a Matrix. Easy

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/

No comments:

Post a Comment