问题描述:
Given a binary matrix A
, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0]
horizontally results in [0, 1, 1]
.
To invert an image means that each 0
is replaced by 1
, and each 1
is replaced by 0
. For example, inverting [0, 1, 1]
results in [1, 0, 0]
.
分析:这道题比较简单,数列倒置后每个数再去异或即可。麻烦的地方在于我是用C写的,要分配内存空间,对于一个平时工作不使用C的人来说徒增了不少困难。而且columnSizes和returnSize也没什么用,但是不更新的话会得不出结果。
int** flipAndInvertImage(int** A, int ARowSize, int *AColSizes, int** columnSizes, int* returnSize) {
int **ans = malloc(ARowSize * sizeof(int*));
*columnSizes = malloc(ARowSize * sizeof(int));
for(int i=0;i<ARowSize;i++){
ans[i] = malloc(AColSizes[i] * sizeof(int));
for(int k=0;k<AColSizes[i];k++){
ans[i][k] = A[i][k];
}
*(*columnSizes + i) = AColSizes[i];
}
for(int j=0;j<ARowSize;j++){
int left=0,right=AColSizes[j]-1;
while(left<right){
//reverse
ans[j][right] = ans[j][right] ^ 0x01;
ans[j][left] = ans[j][left] ^ 0x01;
//swap
int temp;
temp = ans[j][right];
ans[j][right] = ans[j][left];
ans[j][left] = temp;
left++;
right--;
}
if(left == right){
//reverse
ans[j][left] = ans[j][left] ^ 0x01;
}
}
*returnSize = ARowSize;
return ans;
}