题目:
关键词:坐标排序
static int CmpMinor(void const **point0, void const **point1)
{
int x0 = ((int **)point0)[0][0];
int y0 = ((int **)point0)[0][1];
int x1 = ((int **)point1)[0][0];
int y1 = ((int **)point1)[0][1];
int ret = ((x0 * x0) + (y0 * y0)) - ((x1 * x1) + (y1 * y1));
return ret;
}
/**
* 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().
*/
int** kClosest(int** points, int pointsSize, int* pointsColSize, int K, int* returnSize, int** returnColumnSizes)
{
if ((points == NULL) || (pointsSize <= 0) || (pointsColSize == NULL) || (returnSize == NULL) ||
(returnColumnSizes == NULL)) {
return NULL;
}
int i, j;
*returnSize = K;
int **retArray = (int **)malloc(sizeof(int *) * K); /* should be int * */
if (retArray == NULL) {
printf("malloc error\n");
return NULL;
}
qsort(points, pointsSize, 2 * sizeof(int), CmpMinor);
*returnColumnSizes = malloc(sizeof(int *)* K);
for (i = 0; i < MIN(pointsSize, K); i++) {
retArray[i] = (int *)malloc(pointsColSize[i] * sizeof(int));
if (retArray[i] == NULL) {
printf("malloc error\n");
return NULL;
}
for (j = 0; j < pointsColSize[i]; j++) {
// MyDebug("%d ", points[i][j]);
retArray[i][j] = points[i][j];
}
(*returnColumnSizes)[i] = pointsColSize[i];
}
return retArray;
}
网友评论