Concise and effective C++ Code


  • 0
    X

    I have some optimization compare to other code. The point is to add the counter for existing equal distance within every loop instead of recalculating it again in a new loop outside.

     class Solution {
        long distance(pair<int, int> p1, pair<int, int> p2) {
            int d1 = p1.first - p2.first;
            int d2 = p1.second - p2.second;
            return d1 * d1 + d2 * d2;
        }
    public:
        int numberOfBoomerangs(vector<pair<int, int>>& points) {
            int ans = 0;
            for(int i = 0 ; i < points.size(); ++i) {
                unordered_map<long, int> mp;
                for(int j = 0; j < points.size(); ++j) {
                    if(i == j) continue;
                    long dis = distance(points[i], points[j]);
                    // Add the counter for existing equal distance here
                    ans += mp[dis] * 2;  
                    mp[dis]++;
                }
            }
            return ans;
        }
    };
    
    

Log in to reply
 

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