zoukankan      html  css  js  c++  java
  • Line Reflection -- LeetCode

    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:

    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)?

    思路:假设如果存在这样的一条对称轴,那么对于一对对称点,它们的X坐标之和应该是个定值。

    我们找到所有点中X坐标的最小值和最大值,两者之和就是这个定值。

    然后将所有点的坐标记录在set中,然后判断每个点的对称点是否在set中。

    时间复杂度O(N)。

     1 class Solution {
     2 public:
     3     bool isReflected(vector<pair<int, int>>& points) {
     4         if (points.size() == 0) return true;
     5         unordered_set<string> p;
     6         int minX = INT_MAX, maxX = INT_MIN;
     7         for (int i = 0; i < points.size(); i++) {
     8             int x = points[i].first, y = points[i].second;
     9             minX = std::min(minX, x);
    10             maxX = std::max(maxX, x);
    11             string code = std::to_string(x) + "|" + std::to_string(y);
    12             p.insert(code);
    13         }
    14         int sum = minX + maxX;
    15         for (int i = 0; i < points.size(); i++) {
    16             int x = sum - points[i].first, y = points[i].second;
    17             string code = std::to_string(x) + "|" + std::to_string(y);
    18             if (p.count(code) == 0) return false;
    19         }
    20         return true;
    21     }
    22 };
  • 相关阅读:
    .Net Remoting(应用程序域) Part.1(转载)
    .net 中读取自定义Config文件
    WebBrowser控件说明
    Delphi常用技巧 3
    句柄3
    句柄5
    点击TWebBrowser中的超级链接不在新的IE窗口打开
    句柄2
    webbrower
    句柄4
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5821431.html
Copyright © 2011-2022 走看看