美文网首页
leetcode-0973

leetcode-0973

作者: 里卡多伊泽克森多斯桑托斯TV | 来源:发表于2020-04-12 12:36 被阅读0次

题目:

最接近原点的 K 个点

关键词:坐标排序

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;
}

相关文章

  • leetcode-0973

    题目: 最接近原点的 K 个点 关键词:坐标排序

网友评论

      本文标题:leetcode-0973

      本文链接:https://www.haomeiwen.com/subject/fqpvmhtx.html