leetcode 447. Number of Boomerangs

来源:互联网 发布:jdk 7 linux x64.tar 编辑:程序博客网 时间:2024/05/22 15:34

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).

Example:

Input:[[0,0],[1,0],[2,0]]Output:2Explanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
我是先用一个DP二维数组,DP[i][j] 来保存 index为 i 的坐标和 index为 j 的坐标之间的距离。然后以某个点为第一个点,找到与它距离相同的点的group,在每个group中,如果点的数量大于2,就说明出现了boomerangs。
package leetcode;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class Number_of_Boomerangs_447 {public int numberOfBoomerangs(int[][] points) {int n=points.length;double[][] DP=new double[n][n];for(int i=0;i<n-1;i++){for(int j=i+1;j<n;j++){double d2=Math.pow(points[i][0]-points[j][0],2)+Math.pow(points[i][1]-points[j][1],2);double distance=Math.sqrt(d2);DP[i][j]=distance;DP[j][i]=distance;}}int result=0;for(int firstPointIndex=0;firstPointIndex<n;firstPointIndex++){Map<Double,Integer> map=new HashMap<Double,Integer>();for(int i=0;i<n;i++){if(i==firstPointIndex){continue;}int count=map.getOrDefault(DP[firstPointIndex][i], 0);count++;map.put(DP[firstPointIndex][i], count);}Iterator iter = map.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();int val = (int)entry.getValue();if(val>=2){result+=(val*(val-1));}}}return result;}public static void main(String[] args) {// TODO Auto-generated method stubNumber_of_Boomerangs_447 n=new Number_of_Boomerangs_447();int[][] points=new int[][]{{0,0},{1,0},{2,0}};System.out.println(n.numberOfBoomerangs(points));}}
大神没用二维数组,但是想法跟我一样。
public int numberOfBoomerangs(int[][] points) {    int res = 0;    Map<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 d = getDistance(points[i], points[j]);                            map.put(d, map.getOrDefault(d, 0) + 1);        }                for(int val : map.values()) {            res += val * (val-1);        }                    map.clear();    }        return res;}private int getDistance(int[] a, int[] b) {    int dx = a[0] - b[0];    int dy = a[1] - b[1];        return dx*dx + dy*dy;}


原创粉丝点击