LeetCode //C - 1252. Cells with Odd Values in a Matrix

1252. Cells with Odd Values in a Matrix

There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each i n d i c e s i = r i , c i indicesi = r_i, c_i indicesi=ri,ci represents a 0-indexed location to perform some increment operations on the matrix.

For each location indicesi, do both of the following:

  1. Increment all the cells on row r i r_i ri.
  2. Increment all the cells on column c i c_i ci.

Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.

Example 1:

Input: m = 2, n = 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 is \[1,3,1,1,3,1], which contains 6 odd numbers.

Example 2:

Input: m = 2, n = 2, indices = \[1,1,0,0]

Output: 0

Explanation: Final matrix = \[2,2,2,2]. There are no odd numbers in the final matrix.

Constraints:
  • 1 <= m, n <= 50
  • 1 <= indices.length <= 100
  • 0 < = r i < m 0 <= r_i < m 0<=ri<m
  • 0 < = c i < n 0 <= c_i < n 0<=ci<n

From: LeetCode

Link: 1252. Cells with Odd Values in a Matrix


Solution:

Ideas:
  • Instead of updating the whole matrix, only track how many times each row and column is incremented.
  • Use two arrays:
    • rowsi = number of increments on row i
    • colsj = number of increments on column j
  • For each operation r, c, do:
    • rowsr++
    • colsc++
  • A cell (i, j) is incremented rowsi + colsj times.
  • If (rowsi + colsj) is odd, that cell is odd.
  • Count all such cells.
Code:
c 复制代码
int oddCells(int m, int n, int** indices, int indicesSize, int* indicesColSize) {
    int rows[50] = {0};
    int cols[50] = {0};

    for (int i = 0; i < indicesSize; i++) {
        rows[indices[i][0]]++;
        cols[indices[i][1]]++;
    }

    int ans = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if ((rows[i] + cols[j]) % 2 == 1) {
                ans++;
            }
        }
    }

    return ans;
}
相关推荐
语戚3 小时前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp
青山木3 小时前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
是隼人3 小时前
buuctf-pwn [NewStarCTF 2023 公开赛道]stack migration(64位栈迁移)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
这料鬼有毒4 小时前
二刷hot100-1143.最长公共子序列
算法·leetcode·动态规划
政企项目老覃5 小时前
边缘 AI 推理部署:安防零售场景下的模型裁剪与端侧落地实践
人工智能·程序人生·算法·性能优化·vllm
Logic1016 小时前
C语言/数据结构贪心算法题解:买卖股票的最佳时机——一次交易最大利润(O(n)时间O(1)空间)
c语言·数据结构·贪心算法·数组·时间复杂度·算法题·股票交易
Logic1016 小时前
C语言/数据结构位运算题解:异或XOR找出货币交易中的“独特面值“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
GreenTea7 小时前
发布 3 天登顶 HN:不生成一个字的模型 Jev,我把它的源码和黑料都扒了一遍
前端·后端·算法
庖丁解牛7 小时前
无穷小不是一个“神秘小数”,而是一场奔向 0 的过程
算法