美文网首页
LeetCode 1252. Cells with Odd Va

LeetCode 1252. Cells with Odd Va

作者: LiNGYu_NiverSe | 来源:发表于2020-11-26 01:41 被阅读0次

    Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

    Return the number of cells with odd values in the matrix after applying the increment to all indices.

    Example 1:

    Example 1

    Input: n = 2, m = 3, indices = [[0,1],[1,1]]
    Output: 6
    Explanation: Initial matrix = [[0,0,0],[0,0,0]].
    After applying first increment it becomes [[1,2,1],[0,1,0]].
    The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.

    Example 2:

    Example 2:
    Input: n = 2, m = 2, indices = [[1,1],[0,0]]
    Output: 0
    Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.

    Constraints:

    • 1 <= n <= 50
    • 1 <= m <= 50
    • 1 <= indices.length <= 100
    • 0 <= indices[i][0] < n
    • 0 <= indices[i][1] < m

    Solution1:

    class Solution:
        def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
            x, y = [0] * n, [0] * m
            for i in indices:
                x[i[0]] += 1
                y[i[1]] += 1
            return sum([1 for j in y for i in x if (j+i) % 2])
    

    We can think of row and column individually and then use list comprehension to find the summation as each cell (instead of making a matrix explicitly).
    我们可以单独考虑行和列,然后使用列表推导来求出目标矩阵中元素的值(而不是显式地创建矩阵)。

    Solution2

    class Solution:
        
        def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
            matrix = [[0 for i in range(m)] for j in range(n)] 
            
            def inc(x, y):
                for i in range(m):
                    matrix[x][i] += 1
                for i in range(n):
                    matrix[i][y] += 1
                    
            for ind in indices:
                inc(ind[0], ind[1])
                
            return sum([0 if n % 2 == 0 else 1 for l in matrix for n in l])
    

    This solution is to create a matrix explicitly and update each cell of it by creating a function.
    该解决方案是显式创建矩阵并通过创建一个函数来更新矩阵中的每个值。

    相关文章

      网友评论

          本文标题:LeetCode 1252. Cells with Odd Va

          本文链接:https://www.haomeiwen.com/subject/qsaoiktx.html