矩阵其实就是二维数组,这些题目在9日集训中已经做过,这里做的方法大致相同。
int countNegatives(int** grid, int gridSize, int* gridColSize) {
int r = gridSize;
int c = gridColSize[0];
int ret = 0;
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
if(grid[i][j] < 0) ret++;
}
}
return ret;
}
int maximumWealth(int** accounts, int accountsSize, int* accountsColSize) {
int r = accountsSize;
int c = accountsColSize[0];
int max = 0;
for(int i = 0; i < r; ++i) {
int temp = 0;
for(int j = 0; j < c; ++j) {
temp += accounts[i][j];
}
if(temp > max) max = temp;
}
return max;
}
int diagonalSum(int** mat, int matSize, int* matColSize){
//取矩阵行和列长
int r = matSize;
int sum = 0;
for(int i = 0; i < r; ++i) {
sum += mat[i][i];
}
int index = 0;
for(int i = r - 1; i >= 0; --i) {
sum += mat[index++][i];
}
if(r % 2 == 1) sum -= mat[r / 2][r / 2];
return sum;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* rowAndMaximumOnes(int** mat, int matSize, int* matColSize, int* returnSize){
int * ret = (int *)malloc(sizeof(int) * 2);
ret[0] = 0;
ret[1] = 0;
int r = matSize;
int c = matColSize[0];
for(int i = 0; i < r; ++i) {
int sum1 = 0;
for(int j = 0; j < c; ++j) {
if(mat[i][j] == 1) {
sum1++;
}
}
if(sum1 > ret[1]) {
ret[0] = i;
ret[1] = sum1;
}
}
*returnSize = 2;
return ret;
}