1. 程式人生 > 實用技巧 >【leetcode】迴旋鏢的數量

【leetcode】迴旋鏢的數量

int compare(const void* a, const void* b)
{
    return *(int*)a > *(int*)b;
}

int numberOfBoomerangs(int** points, int pointsSize, int* pointsColSize)
{
    if (points == NULL || pointsSize < 3 || pointsSize > 500) {
        return 0;
    }

    int distance[MAX_N] = {0};  // 距離陣列
    int sum = 0
; int i; // 指標,選擇錨點 int j; // 指標,計算距離 for (i = 0; i < pointsSize; i++) { // 計算每一點到點i的距離 for (j = 0; j < pointsSize; j++) { distance[j] = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1
] - points[j][1]); } // 對距離按升序排序 qsort(distance, pointsSize, sizeof(int), compare); int currCount = 1; // 當前計數 // 遍歷排序後的距離,統計個數 for (j = 1; j < pointsSize; j++) { if (distance[j] != distance[j - 1]) { sum += currCount * (currCount - 1
); currCount = 1; } else { currCount++; } } // 記得統計最後一個單詞 sum += currCount * (currCount - 1); } return sum; }