[LeetCode] 356. Line Reflection 直線對稱


 

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:

  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.

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;
    }
};

 

類似題目:

Max Points on a Line

 

參考資料:

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM