wrote a function to solve problem 1282 in leetcode. Everything works fine on my computer. But not on leetcode, I pass the first test, but on the second test it displays strange data. And I can’t understand where he gets this data from.
first test case
second test case
int** groupThePeople(int* groupSizes, int groupSizesSize, int* returnSize, int** returnColumnSizes);
int main(){
int arr[] = {3,3,3,3,3,1,3};
int arr1[] = {2,1,3,3,3,2};
int n = 0;
int** cs = malloc(sizeof(int*));
int** res = groupThePeople(arr, 7, &n, cs);
for (int i = 0; i < n; i++)
{
printf("%dn", cs[0][i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < cs[0][i]; j++)
{
printf("%dn",res[i][j]);
}
}
return 0;
}
int** groupThePeople(int* groupSizes, int groupSizesSize, int* returnSize, int** returnColumnSizes) {
int** res = malloc(sizeof(int*) * groupSizesSize);
*returnColumnSizes = malloc(sizeof(int) * groupSizesSize);
int cs = 0;
int inx = 0;
for(int i = 1; i < groupSizesSize; i++){
if(groupSizes[i - 1] != -1){
*returnSize += 1;
int size = groupSizes[i - 1];
int* t = malloc(sizeof(int) * size);
(*(*returnColumnSizes + cs++)) = size;
for(int j = 0, k = i; j < size; j++, k++){
if(groupSizes[k] == groupSizes[k - 1]){
if (j + 2 == size){
t[j] = k - 1;
groupSizes[k - 1] = -1;
t[j + 1] = k ;
groupSizes[k] = -1;
break;
}
t[j] = k - 1;
groupSizes[k - 1] = -1;
}
else{
t[j++] = k - 1;
groupSizes[k - 1] = -1;
for(int l = i - 1; l < groupSizesSize && j < size; l++){
if(groupSizes[l] == size){
t[j++] = l;
groupSizes[l] = -1;
}
}
}
}
res[inx++] = t;
}
}
return res;
}
I thought that this was due to the fact that I was allocating a lot of memory for returnColumnSizes. I tried resizing using realloc, but it doesn’t help.
6