LeetCode 1252. Cells with Odd Values in a Matrix 矩陣中具有奇數(shù)值的元素(Easy)

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).
我們可以單獨(dú)考慮行和列,然后使用列表推導(dǎo)來求出目標(biāo)矩陣中元素的值(而不是顯式地創(chuàng)建矩陣)。

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.
該解決方案是顯式創(chuàng)建矩陣并通過創(chuàng)建一個(gè)函數(shù)來更新矩陣中的每個(gè)值。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容