Thursday, November 24, 2016

Line Reflection -- LeetCode

[Question]
Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given set of points.
Example 1:
Given points = [[1,1],[-1,1]], return true.
Example 2:
Given points = [[1,1],[-1,-1]], return false.
Follow up:
Could you do better than O(n2)?
Hint:
  1. Find the smallest and largest x-value for all points.
  2. If there is a line then it should be at y = (minX + maxX) / 2.
  3. For each point, make sure that it has a reflected point in the opposite side.

[Analysis]
Suppose the reflection line is x', since each point (x,y) should have its reflection point (x' + x'-x, y) in the input array.  The x' can be calculated by (minX+maxX)/2, or by the average of all x of points. The time complexity is O(N).

[Solution]
class Solution{
    bool isReflected ( vector<pair<int,int>>& points ) {
        if (points.empty()) return true;
        unordered_set<pair<int,int>> pts;
        double line = 0;
        for (auto &p : points) {  
            line += p.first;
            pts.insert( p );
        }
        line /= points.size();
        for (auto& p: points) {
            if (!pts.count( {line + line-p.first, psecond} )  ) return false;
        }
        return true;
     }
};

 

No comments:

Post a Comment