[LeetCode] Line Reflection 鐩寸嚎瀵圭О

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Line Reflection 鐩寸嚎瀵圭О相关的知识,希望对你有一定的参考价值。

鏍囩锛?/p>

 

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.

Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.

 

杩欓亾棰樼粰浜嗘垜浠竴鍫嗙偣锛岄棶鎴戜滑瀛樹笉瀛樺湪涓€鏉″钩琛屼簬y杞寸殑鐩寸嚎锛屼娇寰楁墍鏈夌殑鐐瑰叧浜庤鐩寸嚎瀵圭О銆傞鐩腑鐨勬彁绀虹粰鐨勭浉褰撳厖鍒嗭紝鎴戜滑鍙鎸夌収鎻愮ず鐨勬楠ゆ潵鍋氬氨鍙互瑙i浜嗐€傞鍏堟垜浠壘鍒版墍鏈夌偣鐨勬í鍧愭爣鐨勬渶澶у€煎拰鏈€灏忓€硷紝閭d箞浜岃€呯殑骞冲潎鍊煎氨鏄腑闂寸洿绾跨殑妯潗鏍囷紝鐒跺悗鎴戜滑閬嶅巻姣忎釜鐐癸紝濡傛灉閮借兘鎵惧埌鐩寸嚎瀵圭О鐨勫彟涓€涓偣锛屽垯杩斿洖true锛屽弽涔嬭繑鍥瀎alse锛屽弬瑙佷唬鐮佸涓嬶細

 

瑙f硶涓€锛?/p>

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

 

涓嬮潰杩欑瑙f硶娌℃湁姹傛渶澶у€煎拰鏈€灏忓€硷紝鑰屾槸鎶婃墍鏈夌殑妯潗鏍囩疮鍔犺捣鏉ワ紝鐒跺悗姹傚钩鍧囨暟锛屽熀鏈€濊矾閮界浉鍚岋紝鍙傝浠g爜濡備笅锛?/p>

 

瑙f硶浜岋細

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

 

绫讳技棰樼洰锛?/p>

Max Points on a Line

 

鍙傝€冭祫鏂欙細

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 棰樼洰璁茶В姹囨€?鎸佺画鏇存柊涓?..)

以上是关于[LeetCode] Line Reflection 鐩寸嚎瀵圭О的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 195 Tenth Line

LeetCode第195题---Tenth Line

【Leetcode】356. Line Reflection

Leetcode: Line Reflection

Line Reflection -- LeetCode

[ LeetCode试题 ] 195 Tenth Line