Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points.
Example 1:
Input: [[1,1],[-1,1]]
Output: true
Example 2:
Input: [[1,1],[-1,-1]]
Output: false
Follow up:
Could you do better than O(n2) ?
Hint:
- Find the smallest and largest x-value for all points.
- If there is a line then it should be at y = (minX + maxX) / 2.
- For each point, make sure that it has a reflected point in the opposite side.
Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.
這道題給了我們一堆點,問我們存不存在一條平行於y軸的直線,使得所有的點關於該直線對稱。題目中的提示給的相當充分,我們只要按照提示的步驟來做就可以解題了。首先我們找到所有點的橫坐標的最大值和最小值,那么二者的平均值就是中間直線的橫坐標,然后我們遍歷每個點,如果都能找到直線對稱的另一個點,則返回true,反之返回false,參見代碼如下:
解法一:
class Solution { public: bool isReflected(vector<pair<int, int>>& points) { unordered_map<int, set<int>> m; int mx = INT_MIN, mn = INT_MAX; for (auto a : points) { mx = max(mx, a.first); mn = min(mn, a.first); m[a.first].insert(a.second); } double y = (double)(mx + mn) / 2; for (auto a : points) { int t = 2 * y - a.first; if (!m.count(t) || !m[t].count(a.second)) { return false; } } return true; } };
下面這種解法沒有求最大值和最小值,而是把所有的橫坐標累加起來,然后求平均數,基本思路都相同,參見代碼如下:
解法二:
class Solution { public: bool isReflected(vector<pair<int, int>>& points) { if (points.empty()) return true; set<pair<int, int>> pts; double y = 0; for (auto a : points) { pts.insert(a); y += a.first; } y /= points.size(); for (auto a : pts) { if (!pts.count({y * 2 - a.first, a.second})) { return false; } } return true; } };
類似題目:
參考資料:
https://leetcode.com/problems/line-reflection/description/
https://leetcode.com/discuss/107661/48-ms-short-c-solution
https://leetcode.com/discuss/107761/group-by-y-then-sort-by-x-17ms