1. 程式人生 > 其它 >LeetCode - 447. 迴旋鏢的數量

LeetCode - 447. 迴旋鏢的數量

技術標籤:LeetCodeleetcode演算法c++

描述

給定平面上n 對 互不相同 的點points ,其中 points[i] = [xi, yi] 。迴旋鏢 是由點(i, j, k) 表示的元組 ,其中i和j之間的距離和i和k之間的距離相等(需要考慮元組的順序)。

返回平面上所有迴旋鏢的數量。


示例 1:

輸入:points = [[0,0],[1,0],[2,0]]
輸出:2
解釋:兩個迴旋鏢為 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
示例 2:

輸入:points = [[1,1],[2,2],[3,3]]
輸出:2
示例 3:

輸入:points = [[1,1]]

輸出:0

提示:

n ==points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
所有點都 互不相同

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-boomerangs/

求解

    class Solution {
    public:
        int numberOfBoomerangs(vector<vector<int>> &points) {
            int res = 0;
            const int n = points.size();
            for (int i = 0; i < n; ++i) {
                std::unordered_map<int, int> record;  // <距離, 數量>
                // 以points[i]為樞紐,尋找其他點到points[i]距離並計數,如果某個距離超過兩個點,即可構成滿足題意的組合
                // 假設距離d的點有m個,那滿足的解為m * (m - 1),因為是m中選擇2個的一個排列
                for (int j = 0; j < n; ++j) {
                    if (i != j) {
                        ++record[dis(points[i], points[j])];
                    }
                }

                // 計算以i為樞紐滿足題意的解的數量
                for (auto[dis, count] : record) {
                    res += count * (count - 1);
                }
            }

            return res;
        }

    private:
        // 距離計算函式
        inline int dis(const vector<int> &point1, const vector<int> &point2) const noexcept {
            return (point1[1] - point2[1]) * (point1[1] - point2[1]) +
                   (point1[0] - point2[0]) * (point1[0] - point2[0]);
        }
    };