Concise Java Solution - Beat 97.86%


  • 0

    Idea is in https://discuss.leetcode.com/topic/68139/simple-java-solution-using-hashmap-beats-90.
    It goes even faster after modifications.

    public class Solution {
        public int numberOfBoomerangs(int[][] points) {
            int n = points.length;
            if (n <= 2) return 0; 
            HashMap<Double, Integer> distMap = new HashMap<>();
            int cnt = 0; 
            
            for (int i = 0; i < n; i++) {
                distMap.clear(); 
                
                for (int j = 0; j < n; j++) {
                     // calculate distance, and search HashMap.
                    double dist = distance(points[i], points[j]); 
                    if (distMap.containsKey(dist)) {
                        int val = distMap.get(dist); 
                        cnt += 2 * val; 
                        distMap.put(dist, ++val);
                    } else {
                        distMap.put(dist, 1); 
                    }
                }
            }
            
            return cnt; 
        }
        
        private double distance (int[] p1, int[] p2) {
              return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + 
                               Math.pow(p1[1] - p2[1], 2)); 
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.