There is an m x n
matrix that is initialized to all 0
's. There is also a 2D array indices
where each indices[i] = [ri, ci]
represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i]
, do both of the following:
- Increment all the cells on row
ri
. - Increment all the cells on column
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 <= ri < m
0 <= ci < n
Follow up: Could you solve this in O(n + m + indices.length)
time with only O(n + m)
extra space?
這道題給了一個大小為 m by n 的矩陣,初始化均為0,又給了一個坐標數組 indices,說是對於其中的每個坐標 (r, c),將對應的行和列上的數字分別自增1,最后問數組中有多少個數字是奇數。當然最簡單暴力的解法就是就是遍歷每個坐標,分別將對應的行列上的數字自增1,然后最后再判斷奇偶,雖然這是一道 Easy 的題目,但博主還是懷疑這種方法可能會超時,所以根本就沒有嘗試。對於每個坐標都遍歷一次行和列,實在是不太高效,因為該行和該列可能后面還會多次出現,有沒有辦法能夠一次性統計出某行某列到底需要更新多少次呢?答案是肯定的,這里可以建立兩個數組 rowCnt 和 colCnt,分別來統計某行和某列需要更新的次數。之后遍歷整個初始數組,對於任意位置 (i, j),去 rowCnt 和 colCnt 中取出行i和列j需要的更新次數,二者之和就是當前位置需要增加的數字,直接判斷奇偶,奇數的話加到結果 res 中即可,參見代碼如下:
class Solution {
public:
int oddCells(int m, int n, vector<vector<int>>& indices) {
int res = 0;
vector<int> rowCnt(m), colCnt(n);
for (auto idx : indices) {
++rowCnt[idx[0]];
++colCnt[idx[1]];
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
res += (rowCnt[i] + colCnt[j]) % 2;
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1252
參考資料:
https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/