写的有问题的代码:
/**
* 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().
*/
struct pair
{
int a;
int b;
};
void push( struct pair *queue, struct pair *item, int *size, int maxSize )
{
if( *size < maxSize)
{
int i = (*size);
*size = *size + 1;
while( i > 0)
{
int parent_idx = (i-1)/2;
if(queue[parent_idx].a + queue[parent_idx].b >= item->a + item->b)
{
break;
}
queue[i].a = queue[parent_idx].a;
queue[i].b = queue[parent_idx].b;
i = parent_idx;
}
queue[i].a = item->a;
queue[i].b = item->b;
}
else
{
if(item->a + item->b >= queue[0].a + queue[0].b)
{
return;
}
int i = 0;
while( 2 * i + 1 < *size)
{
int a = 2 * i + 1;
int b = 2 * i + 2;
if( b < *size && (queue[b].a + queue[b].b > queue[a].a+ queue[a].b) )
{
a = b;
}
if( queue[a].a + queue[a].b <= item->a + item->b)
{
break;
}
queue[i].a = queue[a].a;
queue[i].b = queue[a].b;
i = a;
}
queue[i]= *item;
}
}
struct pair * pop( struct pair *queue, int *size)
{
struct pair *p = &queue[0];
struct pair *tmp = &queue[ --(*size)];
int i = 0;
while( 2 * i + 1 < *size)
{
int a = 2 * i + 1;
int b = 2 *i + 2;
if( b < *size && (queue[b].a + queue[b].b > queue[a].a + queue[a].b))
{
a = b;
}
if( queue[a].a + queue[a].b <= tmp->a + tmp->b)
{
break;
}
queue[i] = queue[a];
i = a;
}
queue[i] = *tmp;
return p;
}
int** kSmallestPairs(int* nums1, int nums1Size, int* nums2, int nums2Size, int k, int* returnSize, int** returnColumnSizes){
struct pair *queue = (struct pair *)malloc(sizeof(struct pair) * k);
int queue_size = 0;
int n1 = (nums1Size > k) ? k : nums1Size;
int n2 = (nums2Size > k) ? k : nums2Size;
int i,j;
for(i = 0; i < n1; ++i)
{
for(j = 0; j < n2; ++j)
{
struct pair p = {nums1[i], nums2[j]};
push(queue, &p, &queue_size, k);
}
}
int **ret =(int **)malloc(sizeof(int *) * k);
*returnColumnSizes = (int *)malloc(sizeof(int) * k);
for(i = 0; i < k; ++i)
{
ret[i] = (int *)malloc(sizeof(int) * 2);
(*returnColumnSizes)[i] = 2;
}
i = (queue_size > k) ? k : queue_size;
*returnSize = i;
while ( queue_size > 0 && i >0)
{
struct pair *p = pop(queue, &queue_size);
ret[i-1][0] = p->a;
ret[i-1][1] = p->b;
--i;
}
return ret;
}
问题在
struct pair * pop( struct pair *queue, int *size)
{
struct pair *p = &queue[0];
这里应该直接返回值,而不是地址,因为后面堆顶端会被覆盖。