Leetcode 447. Number of Boomerangs

題目:數組

Given n points in the plane that are all pairwise distinct, 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).數據結構

Find the number of boomerangs. You may assume that n will be at most
500 and coordinates of points are all in the range [-10000, 10000]
(inclusive).code

Example: Input: [[0,0],[1,0],[2,0]]get

Output: 2io

Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and
[[1,0],[2,0],[0,0]]map

解法:數據

這道題主要條件是計算三點中第一個點到第二個點的距離和第一個點到第三個點的距離是否相等,由於順序有關,因此要返回到底有多少排列知足這個條件。因此給定一個點的數組,
要依次選擇每一個點當作第一個點, 依次求出它跟其餘點的距離,若是相等則給結果加一,最後返回總數。di

數據結構:poi

HashMap去存儲距離和這個距離出現的次數。co

代碼:

public int numberOfBoomerangs(int[][] points){
    int result = 0;
    HashMap<Integer, Integer>() map= new HashMap<>();
    for(int i = 0; i < points.length; i++){
        for(int j = 0; j < points.length; j++){
            if(i == j) continue;
            int distance = getDistance(points[i],points[j]);
            map.put(distance, map.getOrDefault(distance,0)+1);
        }
        for(int val : map.values()){
            result += val*(val-1); //知足條件的點的排列組合結果數
        }
        map.clear();
    }

    return result;
}

public int getDistance(int[] point1, int[] point2){
    int x = point1[0] - point2[0];
    int y = point1[1] - point2[1];
    return x*x + y*y;
}
相關文章
相關標籤/搜索