mirror of https://github.com/TheAlgorithms/C
feat: add Difference Between Ones and Zeros in Row and Column (#1183)
* add leetcode Difference Between Ones and Zeros in Row and Column * Update leetcode/DIRECTORY.md Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
parent
e68296c07c
commit
60a0c5947d
|
@ -127,4 +127,5 @@
|
|||
| 2256 | [Minimum Average Difference](https://leetcode.com/problems/minimum-average-difference/) | [C](./src/2256.c) | Medium |
|
||||
| 2270 | [Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | [C](./src/2270.c) | Medium |
|
||||
| 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium |
|
||||
| 2482 | [Difference Between Ones and Zeros in Row and Column](https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/description/) | [C](./src/2482.c) | Medium |
|
||||
| 2501 | [Longest Square Streak in an Array](https://leetcode.com/problems/longest-square-streak-in-an-array/description/) | [C](./src/2501.c) | Medium |
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* Return an array of arrays of size *returnSize.
|
||||
* The sizes of the arrays are returned as *returnColumnSizes array.
|
||||
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
|
||||
*/
|
||||
|
||||
// Calculating ones on each row and column.
|
||||
// Runtime: O(n * m)
|
||||
// Space: O(n + m)
|
||||
int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes){
|
||||
int n = gridSize;
|
||||
int m = gridColSize[0];
|
||||
|
||||
int** result = malloc(gridSize * sizeof(int*));
|
||||
for (int i = 0; i < n; i++){
|
||||
result[i] = malloc(m * sizeof(int));
|
||||
}
|
||||
|
||||
int* onesRows = calloc(n, sizeof(int));
|
||||
int* onesCols = calloc(m, sizeof(int));
|
||||
for (int i = 0; i < n; i++){
|
||||
for (int j = 0; j < m; j++){
|
||||
if (grid[i][j] == 1){
|
||||
onesRows[i] += 1;
|
||||
onesCols[j] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < gridSize; i++){
|
||||
for (int j = 0; j < gridColSize[i]; j++){
|
||||
result[i][j] = onesRows[i] + onesCols[j] - (m - onesRows[i]) - (n - onesCols[j]);
|
||||
}
|
||||
}
|
||||
|
||||
free(onesRows);
|
||||
free(onesCols);
|
||||
|
||||
*returnSize = gridSize;
|
||||
*returnColumnSizes = gridColSize;
|
||||
return result;
|
||||
}
|
Loading…
Reference in New Issue