1. 程式人生 > 其它 >[LeetCode 447.] Number of Boomerangs

[LeetCode 447.] Number of Boomerangs

LeetCode 447. Number of Boomerangs

題目描述

You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Return the number of boomerangs.

Example 1:

Input: points = [[0,0],[1,0],[2,0]]
Output: 2
Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].

Example 2:

Input: points = [[1,1],[2,2],[3,3]]
Output: 2

Example 3:

Input: points = [[1,1]]
Output: 0

Constraints:

  • n == points.length
  • 1 <= n <= 500
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • All the points are unique.

解題思路

題目說的是從平面上不重複的一組點中,任意選取三個點可以組成一個迴旋鏢,問能選出幾組。注意,這裡的迴旋鏢把同一個迴旋鏢計算了兩次。
這裡如果直接三重迴圈遍歷,會超時。解決辦法是利用雜湊表降低複雜度。這裡我們直接列舉迴旋鏢的中點,然後遍歷其兩個尾翼即可。

參考程式碼

/*
 * @lc app=leetcode id=447 lang=cpp
 *
 * [447] Number of Boomerangs
 */

// @lc code=start
class Solution {
public:
    int numberOfBoomerangs(vector<vector<int>>& points) {
        int res = 0;
        unordered_map<int, int> hsmap;
        for (auto&& p : points) {
            hsmap.clear();
            for (auto&& q : points) {
                int dist2 = (p[0]-q[0])*(p[0]-q[0]) + (p[1]-q[1])*(p[1]-q[1]);
                hsmap[dist2]++;
            }
            for (auto&& [k, v]: hsmap) {
                res += v*(v-1);
            }
        } // 雜湊表把列舉時間複雜度從 O(n^3) 降到 O(n^2)
        return res;
    } // AC
};
// @lc code=end