C++ solution using hashmap


  • 0
    J

    1.adjust x-values in order to make y-axis as a central axis.

    2.insert points into a hash map to look for the reflected point. if it finds the reflected point, then remove it from the hash map.

    3.if the hash map is not empty, it means some points do not have their reflected points.

    bool isReflected(vector<pair<int, int>>& points) {
    	double center = 0.0;
    	for (int i = 0; i < points.size(); i++)
    		center += points[i].first;
    	center /= points.size();
    
    	unordered_map<double, unordered_map<int, int>> umap;
    	for (int i = 0; i < points.size(); i++) {
    		if (double(points[i].first) == center) continue;
    
    		double x = double(points[i].first) - center;
    		int y = points[i].second;
    		bool found = false;
    		if (umap.count(-x)) {
    			if (umap[-x][y] > 0) 
    				found = true;
    		}
    
    		if (found) {
    			umap[-x][y]--;
    			if (umap[-x][y] == 0)
    				umap[-x].erase(y);
    			if (umap[-x].size() == 0)
    				umap.erase(-x);
    		}
    		else 
    			umap[x][y]++;
    	}
    
    	return umap.size() == 0;
    }

  • 0
    P

    I tried this solution. It fails several test cases.


  • 0
    J

    yes. you are right. I found some mistakes and fixed it. now, my code works fine. I think the testcases have been updated after I upload the past code.


Log in to reply
 

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